DEV Community

Kamrul Hasan
Kamrul Hasan

Posted on • Edited on

Google firebase authentication setup with react js -Sign in with google step by step.

Step 1: Go to https://firebase.google.com/ {make sure you have logged in with Gmail}.


Step 2: Click on “go to console” of the top right corner of the page.
Image description


Step 3: Click on “Add project” if you are new you will get "Create project" button.

Image description


Step 4: Give a project name in text field and click “Continue” button.

Image description


Step 5: If you want google analytics then enable it otherwise disable it and click “Create project” button.

Image description


Step 6: You will find a window that shows “Your new project is ready” then Click the “continue” button.

Image description


Step 7: Then it will redirect to your project overview page.

Image description


Step 8: In the overview page you will find some icons. Click < / > this icon for the web app registration. Then it will redirect you to the register app page.

Image description


Step 9: In the register app page you have to provide the register app name. Provide a meaningful name related to your project and click on the “Register app” button.

Image description


Step 10: Then you have to add firebase SDK(Software Development Kit) to your react app using this command in the terminal of your project directory. You can use VsCode terminal or windows console. Here I used VsCode terminal.

npm install firebase
Enter fullscreen mode Exit fullscreen mode

Image description


Step 11: Initialize Firebase and begin using the SDKs . Import the functions you need from the SDKs **. [Create a file named ex: (firebase.init.js** )inside the src **folder in your react application]
copy the code and paste it in the **firebase.init.js
file. [note: I changed the config info for security reason, this config file should not disclose in public]

Do not forget to export app at end of the code inside the firebase.init.js. export default app;

Image description

// 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: "Acvz33SyBrd-adTcvxZkGHrQe8Vp58w-rXpmdkV0sg",
  authDomain: "my-firebase-app-8252c.firebaseapp.com",
  projectId: "my-firebase-app-8252c",
  storageBucket: "my-firebase-app-8242c.appspot.com",
  messagingSenderId: "606653287156",
  appId: "1:668612387167:web:ca5305s235567e7833213eca"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
export default app;
Enter fullscreen mode Exit fullscreen mode

Image description


Step 12: After completing the firebase installation and Import the functions you need from the SDKs Click the “Continue to console” button then it will redirect to the project overview page.

Image description


Step 13: Click on Authentication icon from the left sidebar of project overview page.

Image description


Step 14: Then you will redirect to this page, and click** "Get started"** button.

Image description


Step 15: After that you will get an Authentication page like this image and click on “Google” button.

Image description


Step 16: You will find another page like this image and enable this feature, project public-facing name and , provide project support email. Then click on the “Save” button.

Image description


Step 17: Now your google sign-in authentication provider is enabled.

Image description


Step 18: Now click on the “Project settings” icon on the left sidebar scroll down and you will find “Link to a firebase hosting site” click this button.

Image description


Step 19: You will get a popup window like this image. Select your project name which will be hosted and click the “link” button.

Image description


Step 20: After that it will be Linked Firebase Hosting site . see the below image.

Image description


Step 21: Now click on Go to docs top right corner.

Image description


Step 22: You will redirect to this page and hover on the** Build** menu item and select Authentication and click on it.

Image description


Step 23: Then go to the left sidebar of this page and select Authentication>Web>Google then you will get Authenticate Using Google with JavaScript instruction page. You will get here all the instructions that you can implement.

Image description


Step 23-a: Create an instance of the Google provider object. Import this google provider in your project file inside the src *folder *( ex: app.js).

import { GoogleAuthProvider } from "firebase/auth";

const provider = new GoogleAuthProvider();

Enter fullscreen mode Exit fullscreen mode

Step 23-b: Import **getAuth** from **firebase/auth** inside the **app.js** file.

import { getAuth } from "firebase/auth";

const auth = getAuth();

Enter fullscreen mode Exit fullscreen mode

Step 23-c: Import **signInWithPopup** from **firebase/auth** inside the app.js file and pass the **auth** and **provider** parameter.

signInWithPopup(auth, provider)
Enter fullscreen mode Exit fullscreen mode

Step 23-d: Add a onClick handler inside the **App()** function. And pass this handler in Sign-in button.

  const hadleGoogleSignIn = () => {

  }

Enter fullscreen mode Exit fullscreen mode

Step 23-e: Write the following code inside the **App()** function with useState() hook **const [user, setUser] = useState({});** where useris state value and setUseris a state function. This block of code will be inside the hadleGoogleSignIn onClick handler function.

signInWithPopup(auth, provider)
  .then((result) => {
    const user = result.user;
    setUser(user);
    console.log(user)

  }).catch((error) => {
  console.log(error);
  });

Enter fullscreen mode Exit fullscreen mode

Step 23-f: Put this above block of code inside the **hadleGoogleSignIn **onClick handler function.

const hadleGoogleSignIn = () => {
signInWithPopup(auth, provider)

  .then((result) => {
    const user = result.user;
    setUser(user);
    console.log(user)

  }).catch((error) => {
  console.log(error);
  });

 }

Enter fullscreen mode Exit fullscreen mode

Step 23-g: Add **SignOut** onClick handler inside the App() function. Also import signOut from **firebase/auth.**.

  const handleSignOut = () => {
    signOut(auth)
      .then(() => {
        setUser({});
      })
      .catch(error => {
        setUser({});
      })
  }

Enter fullscreen mode Exit fullscreen mode

Step 23-h: Finally return the data on the UI for display . this block of code will be inside the **App()** function.

  return (
    <div className="App">
      {
        user.email ? <button onClick={handleSignOut}>Sign Out</button> :
            <button onClick={hadleGoogleSignIn}>Sign in With Google</button>
      }
      <div>
        <h3>{user.displayName}</h3>
        <h5>{user.email}</h5>
        <img src={user.photoURL} alt="" />
      </div>
    </div>
  );

Enter fullscreen mode Exit fullscreen mode


Full code inside the firebase.init.js file

// 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: "Acvz33SyBrd-adTcvxZkGHrQe8Vp58w-rXpmdkV0sg",
  authDomain: "my-firebase-app-8252c.firebaseapp.com",
  projectId: "my-firebase-app-8252c",
  storageBucket: "my-firebase-app-8242c.appspot.com",
  messagingSenderId: "606653287156",
  appId: "1:668612387167:web:ca5305s235567e7833213eca"
};

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

Enter fullscreen mode Exit fullscreen mode


Full code inside the app.js file

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

const auth = getAuth(app);

function App() {
  const [user, setUser] = useState({});

  const provider = new GoogleAuthProvider();

  const hadleGoogleSignIn = () => {
    signInWithPopup(auth, provider )
      .then(result => {
        const user = result.user;
        setUser(user);
        console.log(user)
      })
      .catch(error => {
        console.log(error);
      })
  }

  const handleSignOut = () => {
    signOut(auth)
      .then(() => {
        setUser({});
      })
      .catch(error => {
        setUser({});
      })
  }

return (
    <div className="App">
      {
        user.email ? <button onClick={handleSignOut}>Sign Out</button> :
        <button onClick={hadleGoogleSignIn}>Sign in WithGoogle</button>
      }
      <div>
        <h3>{user.displayName}</h3>
        <h5>{user.email}</h5>
        <img src={user.photoURL} alt="" />
      </div>
    </div>
  );
}

export default App;


Enter fullscreen mode Exit fullscreen mode

Top comments (0)