DEV Community

Cover image for How to Implement Firebase Google Authentication with ReactJS
Hamzat Abdul-muizz
Hamzat Abdul-muizz

Posted on • Updated on

How to Implement Firebase Google Authentication with ReactJS

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:

yarn create vite
Enter fullscreen mode Exit fullscreen mode

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

Your Application Structure


Setting Up Firebase:

  1. Start by creating an account on Firebase here here.
  2. Once logged in, access the Firebase Console by clicking the "Go to console" button in the top right corner.

Firebase Console

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

Firebase dashboard

  1. Navigate to the web icon and follow the steps to register your app. Skip Firebase Hosting for now.
  2. 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

Selection Of Google Provider



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':
import { getAuth, GoogleAuthProvider } from "firebase/auth";
export const auth = getAuth(app);
export const googleProvider = new GoogleAuthProvider();
Enter fullscreen mode Exit fullscreen mode

firebase authentication setup

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:

yarn add react-firebase-hooks
Enter fullscreen mode Exit fullscreen mode

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

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
}
Enter fullscreen mode Exit fullscreen mode

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

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>
      )}
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Authentication Component


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

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

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

  // ... previous code ...
}
Enter fullscreen mode Exit fullscreen mode

Logout Implementation


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


Top comments (1)

Collapse
 
envitab profile image
Ekemini Samuel

Great article!

Keep up the good work @canhamzacode