React Sign In using Firebase Google Authentication

ReactJs Sign-In forms Integration with Firebase services to enable a user to sign-in using Google Authentication. We are focusing on how to make them work with a perspective of a real-world large project.

Firebase is a group of powerful services that are provided by Google. It is consists of many awesome features that can be used for testing, no-SQL databases, Social and non-social authentication, machine learning, hosting etc.

In this tutorial, we will only have a look at Firebase integration with ReactJs application and Google Authentication.

Integrate Firestore with ReactJs Application

Before we proceed, we need to SignUp/SignIn Google Firebase then a create a project to fetch configuration object to connect our ReactJs app with Firebase.

Step 1) Visit the Firebase Console and create a project

React Sign In using Firebase Google Authentication

Step 2) Setup Web Application. Click on Project Overview then Web icon to Register the app

React Sign In using Firebase Google Authentication

Step 3) Get your project credentials. Click on the app then the gear icon. Now scroll down in General tab to get credentials under the Config tab.

React Sign In using Firebase Google Authentication

Install Firebase Package in ReactJs Application

Now we will install NPM package for Firebase by executing below command:

$ npm install firebase

Create Firebase Utils File

Under the project root create a new folder firebase with a file firebase.utils.js then update it with below code:

// firebase.utils.js
import firebase from 'firebase/app';
import 'firebase/auth';

const config = {
    apiKey: "AIzaSyAaelwlWRauYkQFSJDCbGxaRJyF7ACHtcU",
    authDomain: "react-lessons-ded34.firebaseapp.com",
    databaseURL: "https://react-lessons-ded34.firebaseio.com",
    projectId: "react-lessons-ded34",
    storageBucket: "react-lessons-ded34.appspot.com",
    messagingSenderId: "664185367220",
    appId: "1:664185367220:web:5db3f261d498df12d205e1"
};

firebase.initializeApp(config);

export const auth = firebase.auth();

const provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({ prompt: 'select_account' });
export const signInWithGoogle = () => auth.signInWithPopup(provider);

export default firebase;

Enable Google Authentication in Firebase

For using Google Authentication service in Firebase, we need to enable it.

Click on Authentication on the left sidebar, then enable Google and Email/Password under Sign-in methods tab:

React Sign In using Firebase Google Authentication

Modify State in App Component

Now we need to put a state in App component by converting it into a class component as shown below and defining a state with property currentUser

So our final App.js file will look like this:

// App.js
import React from 'react';
import './App.css';

import { signInWithGoogle } from './firebase/firebase.utils';
import { auth } from './firebase/firebase.utils';

class App extends React.Component {

  constructor() {
    super();

    this.state = {
      currentUser: null
    };
  }

  unsubscribeFromAuth = null;

  componentDidMount() {
    this.unsubscribeFromAuth = auth.onAuthStateChanged(user => {
      this.setState({ currentUser: user });
    });
  }

  componentWillUnmount() {
    this.unsubscribeFromAuth();
  }

  render() {
    return (
      <div className='user-info'>
        {

          this.state.currentUser ?

            (<div>
              <div>
                <img src={this.state.currentUser.photoURL} />
              </div>
              <div>Name: {this.state.currentUser.displayName}</div>
              <div>Email: {this.state.currentUser.email}</div>

              <button onClick={() => auth.signOut()}>LOG OUT</button>
            </div>
            ) :

            <button onClick={signInWithGoogle}>SIGN IN WITH GOOGLE</button>

        }
      </div >
    );
  }
}


export default App;

In the above code, we calling signInWithGoogle method to open a popup to sign in using Google Account.

The onAuthStateChanged method will be called as a callback on module load and even after a sign which we are calling in the componentDidMount component class hook cycle method.

To sign out current use we simply call signOut method on auth class.

We are ready to test by running the following command

$ npm start

 

Conclusion

In about tutorial, we discussed How to add Firebase services in a React application and also how to use Google Authentication to sign in a user and fetch its details which can be saved in the Firebase Firestore database which we will discuss in next tutorial.

 

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments