Open In App

How to implement Google Login in your Web app with Firebase ?

Firebase offers a great number of options to implement Login in your app. Some of which are:

The best part is you don’t have to worry about handling the login flow, Firebase takes care of it.



Approach:

First of all, create a Firebase project by following these steps:



<!– Insert these scripts inside your body tag –>

<body>

<!–This is the most important script that has to be added –>

<script src=”/__/firebase/7.14.4/firebase-app.js”></script>

<!– In order to use Google login add this script –>

<script src=”/__/firebase/7.14.4/firebase-auth.js”></script>
</body>

var firebaseConfig = {
  apiKey: "your-api-key",
  authDomain: "your-project-id.firebaseapp.com",
  databaseURL: "https://your-project-id.firebaseio.com",
  projectId: "your-project-id",
  storageBucket: "your-project-id.appspot.com",
  messagingSenderId: "the-sender-id",
  appId: "the-app-id",
  measurementId: "G-measurement-id",
};

Now, we will enable google login in our app by following these steps:

const GoogleAuth = new firebase.auth.GoogleAuthProvider();
//To sign in with pop-up.
firebase.auth().signInWithPopup(googleAuth);

//To sign in with redirect. 
firebase.auth().signInWithRedirect(googleAuth);

Example:

We will create a simple react based web app with just the login button.

Code for the button component:




import React, { Component } from "react";
import firebase from 'firebase';
  
class tutorial extends Component{
render(){
return(
<div>
   <button
         onClick={() => {
           
     // Google provider object is created here.
    const googleAuth = 
          new firebase.auth.GoogleAuthProvider();
               
    // using the object we will authenticate the user.
    firebase.auth().signInWithPopup(googleAuth);
                    }} >
          Sign in with Google
    </button>
 </div>
   );
  }
 }
 export default tutorial;

Code for your Firebase.ts file:




import * as firebase from 'firebase';
const firebaseConfig = {
  apiKey: "****",
    authDomain: "****.firebaseapp.com",
    databaseURL: "https://*****.firebaseio.com",
    projectId: "****",
    storageBucket: "****.appspot.com",
    messagingSenderId: "****",
    appId: "****",
    measurementId: "****"
};
class Firebase {
  constructor() {
    firebase.initializeApp(firebaseConfig);
  }
}
  
export default Firebase;

Output:


Article Tags :