Firebase V9 LogIn with Google in React and NextJS
Tags: webdev, react, javascript, firebase
Published: 2021-11-07 15:49:08

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](https://dev.to/shareef/context-api-with-typescript-and-next-js-2m25)

Enough of talking, Let's get started.

### 1. Install firebase

```npm
npm install firebase
```

### 2. Firebase setup

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

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

### 3. Setting up auth functionality

```tsx
//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");
};


```

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

### 4. Implementing login and logout functionality

```tsx

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

```

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.

```ts
// 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");
        }
    });
}, []);
```

Thanks for reading, I have used ContextAPI here, you can read my blog on [ContextAPI with NextJS and TypeScript](https://dev.to/shareef/context-api-with-typescript-and-next-js-2m25)

Closing here 👋👋👋
> This is **Shareef**.
> My recent project [yourounotes](https://yourounotes.vercel.app/)
> My [Portfolio](https://portfolio.shareef.vercel.app/)
> Twitter [ShareefBhai99](https://twitter.com/shareefBhai99)
> [Linkedin](https://www.linkedin.com/in/nadeem-shareef-7a8394182/)
> My [other Blogs](https://dev.to/shareef)