How to Implement Firebase Google Authentication with ReactJS
Tags: react, firebase, google, tutorial
Published: 2023-08-09 09:15:59

## Introduction
Google Authentication, a software-based authentication method, utilizes the Time-based One Time Password (TOTP) mechanism for multifactor authentication. In this comprehensive guide, suitable for developers of all levels, we will delve into implementing Google Authentication into your ReactJS application. We'll explore best practices and offer solutions to potential errors you might encounter during the integration process. Familiarity with JavaScript and ReactJS is assumed for this tutorial. Please note that while we will use 'yarn' for package management, you can substitute 'npm' wherever applicable.



---

## Setting Up Your React App
To begin, create your React app and install ReactJS if you haven't already:

```bash
yarn create vite
```

Once your server is up and running, you'll have a structure similar to this:

 


![Your Application Structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4wqy74hddw8u9tq9agl4.png)



---

**Setting Up Firebase:**
1. Start by creating an account on Firebase here [here](https://firebase.google.com/).
2. Once logged in, access the Firebase Console by clicking the "Go to console" button in the top right corner.

![Firebase Console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jhnmevs9fs1r6ymyj4pz.png)


3. Click "Add project" and provide a project name in the input field. Then, click "Continue."
4. Skip enabling Google Analytics for this tutorial and proceed by clicking "Create project."
5. After a brief setup period, you'll be redirected to a new page resembling this:




![Firebase dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y6rsssyjymq12rivicwv.png)


 

6. Navigate to the web icon and follow the steps to register your app. Skip Firebase Hosting for now.
7. Copy the provided Firebase Software Development Kit (SDK).


---
**Setup Authentication for the App**
1 Navigate to your dashboard for this particular project.
2 Click on Authentication button after which you will select google as your provider
 


![setting up authentication](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/132aj246hv3weeazprt6.png)

![Selection Of Google Provider](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1xbnhp2hjzmorejz1uf7.png)




 
---

---

**Configuring Firebase in Your App:**
1. Inside the 'src' folder, create a 'config' folder and a new file 'firebase.jsx.'
2. Paste the previously copied Firebase SDK into 'firebase.jsx'.
3. Import 'auth' and 'googleAuthProvider' from 'firebase/auth':

```jsx
import { getAuth, GoogleAuthProvider } from "firebase/auth";
export const auth = getAuth(app);
export const googleProvider = new GoogleAuthProvider();
```



![firebase authentication setup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9eq6msclilecrvdn18qx.png)




**Note: Make sure you don’t push your secret key to github**

---



**Installing Dependencies:**
Now, let's install 'react-firebase-hooks' to handle data persistence:

```bash
yarn add react-firebase-hooks
```



---

**Implementing Google Authentication:**
In the component where you plan to handle authentication, import necessary modules and create the 'signInWithGoogle' function:


```jsx
import { auth, googleProvider } from './config/firebase';
import { signInWithPopup } from 'firebase/auth';
import { useAuthState } from 'react-firebase-hooks/auth';

function YourComponent() {
  const [user] = useAuthState(auth);

  const signInWithGoogle = async () => {
    try {
      await signInWithPopup(auth, googleProvider);
    } catch (error) {
      console.error("Error signing in with Google:", error);
    }
  };

  // ... rest of your component code
}
```


---

**Displaying Authentication Status:**
You can now show the user's authentication status in your component:

```jsx
function YourComponent() {
  const [user] = useAuthState(auth);

  // ... previous code ...

  return (
    <>
      {user ? (
        <>
          <h1>Hello, {user?.displayName}</h1>
          <button onClick={handleLogout}>Log out</button>
        </>
      ) : (
        <button onClick={signInWithGoogle}>Sign In with Google</button>
      )}
    </>
  );
}
```


![Authentication Component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8gklkwimvffsnurthklt.png)




---

**Logging Out:**
Implement the 'handleLogout' function to allow users to sign out:

```jsx
function YourComponent() {
  const [user] = useAuthState(auth);

  const handleLogout = () => {
    auth.signOut();
  };

  // ... previous code ...
}
```
 

![Logout Implementation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s8xnt82mp0p4q0co9dym.png)


---

**Conclusion:**
Congratulations! You've successfully integrated Google Authentication into your ReactJS app using Firebase. You've learned to handle user authentication, implement sign-in with Google, and enable sign-out functionality. Feel free to explore further by customizing the user interface and expanding your application's capabilities. If you found this guide helpful, please consider giving it a thumbs up and follow for more valuable content. See you in the next tutorial!

Link to the GitHub repository [here](https://github.com/canhamzacode/Firebase-Google-Authentication)

---