Google firebase authentication setup with react js -Sign in with google step by step.
Tags: firebase, firebaseauthentication, javascript, react
Published: 2022-04-06 15:57:05

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/piakb8apl8reqc5iczrw.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8da4tli9lp789s3h91yw.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r7ok0i3ck8z8zq20yha9.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jnenl4tmgpz7w3egoun6.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j2khwbk88ugorm5lq1cq.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t5gjn881l4gpw9fcjfvd.png)

---
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/05mxnl1mwaar2w15buip.png)

---
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8h6imbhs6m0c52vfs1b3.png)

---
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
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1jpuj5g7rplkon1urvtm.png)

---
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xe31u3rztlbxu39j7tiz.png)

```
// 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;
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hwxivgu41ov21dsxww89.png)

---
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b0gtaooloxuf9k556vxh.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pw94vewhcg9yn9qmg4hy.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pkeorm1a0i7t8dz0a7zs.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2tr1md4mot4aabkwu211.png)

---
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cmlug7dw9t4e7il07coc.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ob05n02nkfofkp1kt8a1.png)

---
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t4ct3nkijekm9e65zpaq.png)

---
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9o0q1ofy4u5r3wmvmgi4.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lcgnsxa3n59pqt39vj8o.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ulm306dtztfmfsk7ezrn.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qitpqj43mi411igu3ryt.png)

---
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uuub79zr1nw57rdoumpm.png)

---
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();

```

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

```
import { getAuth } from "firebase/auth";

const auth = getAuth();

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

```
signInWithPopup(auth, provider)
```

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

```
  const hadleGoogleSignIn = () => {

  }

```

---
Step 23-e: Write the following code inside the `**App()**` function with **`useState()`** hook `**const [user, setUser] = useState({});**` where `user `is state value and `setUser `is 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);
  });

```

---
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);
  });

 }

```

---
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({});
      })
  }

```

---
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>
  );

```

---

---
**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;

```

---

---
**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;


```