Nadeem Shareef

Firebase V9 LogIn with Google in React and NextJS

The easiest way to add authentication to your web app is through Firebase authentication.

Before continuing with adding authentication, make sure to add firebase to your project. And I am using Context API as we need authentication on every page of the web app.

The blog doesn't show how to setup context. You can see my other blog on ContextAPI using NextJS and TypeScript

Enough of talking, Let's get started.

1. Install firebase

npm install firebase
Enter fullscreen mode Exit fullscreen mode

2. Firebase setup

import { initializeApp, getApps } from "firebase/app";
import { getAuth } from "firebase/auth";

const firebaseConfig = {
    apiKey: "apiKey",
    authDomain: "authDomain",
    projectId: "projectID",
    storageBucket: "storageBucket",
    messagingSenderId: "messagingSenderID",
    appId: "appID",
    measurementId: "measurementID",
};

if (!getApps().length) {
    initializeApp(firebaseConfig);
}

export const auth = getAuth();

export default firebaseConfig;
Enter fullscreen mode Exit fullscreen mode

here we are initializing the firebase app then exporting the getAuth function as auth.

3. Setting up auth functionality

//Inside the AuthContext file.

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

// Inside AuthProvider
const provider = new GoogleAuthProvider();

const login = () => {
    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;
            console.log({ credential, token, 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.email;
            // The AuthCredential type that was used.
            const credential = GoogleAuthProvider.credentialFromError(error);
            console.log({ errorCode, errorMessage, email, credential });
        });
};

const logout = () => {
    auth.signOut();
    console.log("logout");
};


Enter fullscreen mode Exit fullscreen mode

Now as login and logout functions are ready, It's time to use them.

4. Implementing login and logout functionality


// Import useAuth from context
import { useAuth } from "../context/AuthContext";

// Destructure login and logout functions.
const { login, logout } = useAuth();

...

return (
    <div>
        <button onClick={login}> Login </button>
        <button onClick={logout}> Logout </button>
    </div>
);

Enter fullscreen mode Exit fullscreen mode

Login and Logout functions are not enough, we also need to listen if the used is login or not, on their next visit.

5. Listening to the auth state.

// Inside Context.
import { useEffect } from "react";
import { onAuthStateChanged } from "firebase/auth";

useEffect(() => {
    onAuthStateChanged(auth, (user) => {
        if (user) {
            const uid = user.uid;
            console.log({ uid });
        } else {
            console.log("no user");
        }
    });
}, []);
Enter fullscreen mode Exit fullscreen mode

Thanks for reading, I have used ContextAPI here, you can read my blog on ContextAPI with NextJS and TypeScript

Closing here 👋👋👋

This is Shareef.
My recent project yourounotes
My Portfolio
Twitter ShareefBhai99
Linkedin
My other Blogs