DEV Community

Cover image for Google Sign-in Sign-out using Firebase Authentication React js step by step
bappasaha
bappasaha

Posted on

Google Sign-in Sign-out using Firebase Authentication React js step by step

The output is below

Image description

Getting Started Firebase Authentation:

πŸ”₯πŸ”₯πŸ”₯ Full Process is here πŸ”₯πŸ”₯πŸ”₯:

πŸ”₯ Steps: 1

  1. visit console.firebase.com.
  2. Create a new project example:

     simple-firebase-authentaion
    
  3. Click --> Go to docs

  4. Click --> Build-->Authentication

  5. Click --> Web--> Get Started

πŸ”₯ Steps: 02

This is only the first time

  1. If you haven't already, install the Firebase JS SDK and initialize Firebase.

Step 1: Create a Firebase project and register your app

This part is already done
https://firebase.google.com/docs/web/setup?authuser=0#create-firebase-project-and-app

βž• Create a Firebase Project

βž• Register your app:
https://firebase.google.com/docs/web/setup?authuser=0#register-app

Register web app -->firebase project home --> Click Web -->give name and register

Step 2: Install the SDK and initialize Firebase

npm install firebase
Enter fullscreen mode Exit fullscreen mode

And we find the firebase version in package.json file under the dependency section

```js
   "dependencies": {
    ...
    "firebase": "^9.16.0",
    ...
    },
Enter fullscreen mode Exit fullscreen mode


## Then, initialize Firebase and begin using the SDKs for the products you'd like to use.



```js

    // Import the functions you need from the SDKs you need
    import { initializeApp } from "firebase/app";
    // TODO: Add SDKs for Firebase products that you want to use
    // https://firebase.google.com/docs/web/setup#available-libraries

    // Your web app's Firebase configuration
    const firebaseConfig = {
    apiKey: "AIzaSyAVpxUgSErILZPX6NHCx6MOk_crJnz89FQ",
    authDomain: "simple-firebase-authenta-1099f.firebaseapp.com",
    projectId: "simple-firebase-authenta-1099f",
    storageBucket: "simple-firebase-authenta-1099f.appspot.com",
    messagingSenderId: "231717497457",
    appId: "1:231717497457:web:ac41abbf092cd9958a49d0"
    };

    // Initialize Firebase
const app = initializeApp(firebaseConfig);

Enter fullscreen mode Exit fullscreen mode

πŸ”₯ Steps:03

  1. Now making a folder name src/firebase/firebase.init.js

now paste the config SDKs into the firebase.init.js this firebase config is different to yours

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "AIzaSyAVpxUgSErILZPX6NHCx6MOk_crJnz89FQ",
  authDomain: "simple-firebase-authenta-1099f.firebaseapp.com",
  projectId: "simple-firebase-authenta-1099f",
  storageBucket: "simple-firebase-authenta-1099f.appspot.com",
  messagingSenderId: "231717497457",
  appId: "1:231717497457:web:ac41abbf092cd9958a49d0"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

export default app;

Enter fullscreen mode Exit fullscreen mode

πŸ”₯πŸ”₯πŸ”₯πŸ”₯πŸ”₯πŸ”₯ For Google Sign in πŸ”₯πŸ”₯πŸ”₯πŸ”₯πŸ”₯πŸ”₯πŸ”₯

Click --> Build-->Authentication-->Get Started
Click --> Build-->Authentication-->Google

Enable google sign-in method by doing πŸ‘‡
Click --> Build-->Authentication-->User-->Set up sign-in method-->Google and Click the enable-icon enable it and give the email to project support email bappa@saha.com and save it.

πŸ‘‰ Follow steps 1 and 5 for the documentaion of firebase after click Web-->Google
1.Create an instance of the Google provider object


    import { GoogleAuthProvider } from "firebase/auth";
    const provider = new GoogleAuthProvider();
Enter fullscreen mode Exit fullscreen mode

5.To sign in with a pop-up window, call signInWithPopup

import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";

const auth = getAuth();
signInWithPopup(auth, provider)
  .then((result) => {
    // This gives you a Google Access Token. You can use it to access the Google API.
    const credential = GoogleAuthProvider.credentialFromResult(result);
    const token = credential.accessToken;
    // The signed-in user info.
    const user = result.user;
    // ...
  }).catch((error) => {
    // Handle Errors here.
    const errorCode = error.code;
    const errorMessage = error.message;
    // The email of the user's account used.
    const email = error.customData.email;
    // The AuthCredential type that was used.
    const credential = GoogleAuthProvider.credentialFromError(error);
    // ...
  });

Enter fullscreen mode Exit fullscreen mode

Now we need a google auth provider so now make this auth provider . We do this
task to App.js file for now .


import './App.css';
import { getAuth, GoogleAuthProvider, signInWithPopup,signOut} from "firebase/auth";
import app from './firebase/firebase.init';
import { useState } from 'react';

const auth =getAuth(app);

function App() {

  const [user, setUser]=useState({});
  const provider = new GoogleAuthProvider()

  const handleGoogleSingIn =()=>{
    signInWithPopup(auth,provider)
      .then(result =>{
        const user =result.user;
        console.log(user)
        setUser(user)
      })
      .catch(error =>{
        console.error('Error is: ',error);
      })

  };

  const handleSignOut =()=>{
    signOut(auth).then(() => {
      setUser({});
      // Sign-out successful.
    }).catch((error) => {
      setUser({});
      // An error happened.
    });
  }


  return (
    <div className="App">
     <button style={{fontSize:'30px',height:'100px', width:'300px',marginTop:'500px'}} onClick={handleGoogleSingIn}>🟒Google Sign In </button>
     <button onClick={handleSignOut} style={{marginTop:'50px',width:'200px', padding:'10px',fontSize:'20px'}} >Sign Out ❌</button>
     <div>

     <p>🧝User Name:πŸ‘‰ <b>{user.displayName}</b></p>
     <span>Email πŸ‘‰ <b>{user.email}</b></span>
     <p>uid πŸ‘‰ <b>{user.uid}</b></p>

     <img style={{height:'100px'}} src={user?.photoURL} alt="image"/>

     </div>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Summary of the whole system:

πŸ‡§πŸ‡© Initital Setup
1. visit: console.firebase.google.com 
2. create a new firebase project
3. Visit doc ( go to docs): Build > Authentication > web > Getting started
4. Register web app > firebase project home > click Web > give name and register
5. Install firebase for your project: npm install firebase
6. Get firebase config and put it in firebase.init.js
7. export app from **firebase.init.js**
Enter fullscreen mode Exit fullscreen mode
πŸ‡§πŸ‡© SETUP THE PROVIDER
8. create auth using getAuth from firebase by using app from firebase.init.js
9. create a google auth provider. do not forget to use  new GoogleAuthProvider(); 
10. go to firebase > Build > Authentication > Sign In method 
11. Enable google sign in method 
12. Create a button for google sign in method with a click handler
13. inside the event handler, call singInWithPopup with auth, provider
14. after singInWithPopup .then result , error 
Enter fullscreen mode Exit fullscreen mode
πŸ‡§πŸ‡© DISPLAY DATA
ADD A NEW SIGN IN METHOD
1. enable the sign in  method
2. Create github, twitter, fb, etc. app create
Enter fullscreen mode Exit fullscreen mode

Here is the overall solution of google sign in and sign out process.
Thanks for reading my blog ...

Top comments (0)