DEV Community

MonkeyScript
MonkeyScript

Posted on

Google Authentication using Firebase in Next.js

Image description

Hellooo everyone,

I was recently developing a platform in Next.js and needed to incorporate Google authentication. The majority of the available guides, however, were out of date, contained errors, or relied on unnecessary dependencies. Anyway, I cracked it and decided that writing it down step by step would be helpful to others. The sole purpose of this article is to walk you through the simplest method of adding Google auth to your Next.js project using Firebase.

Before we begin, I’m assuming you already have a firebase account set up for your project. If this is not the case, please refer to the setup documentation. It’s quite simple. Simply start a new project and register your app. After that, you’ll be given a unique set of credentials. This can be found in your project settings and will look something like,

const firebaseConfig = {
  apiKey: "your api key",
  authDomain: "your credentials",
  projectId: "your credentials",
  storageBucket: "your credentials",
  messagingSenderId: "your credentials",
  appId: "your credentials"
};
Enter fullscreen mode Exit fullscreen mode

Now that we have the Firebase project set up, let’s get started on the coding.

Step 1 : Creating a Next.js project

npx create-next-app _PROJECT_NAME_
Enter fullscreen mode Exit fullscreen mode

Step 2 : Install the Firebase module

npm install firebase 
Enter fullscreen mode Exit fullscreen mode

The version I used was 9.9.4.

Step 3 : Enable Google sign-in method

Navigate to the authentication tab in your Firebase project. You will be able to see various sign-in methods that have been configured with the project. Add a new Google provider here.

Image description

Step 4 : Enable authentication in your project

Yes, this is the exciting part. Let’s keep things simple and keep all of the authentication logic in the _app.js file.

Let’s start by importing the firebase modules and adding our firebase credentials to the project.

import firebase from "firebase/compat/app";
import "firebase/compat/auth";

const firebaseConfig = {
  apiKey: "your api key",
  authDomain: "your credentials",
  projectId: "your credentials",
  storageBucket: "your credentials",
  messagingSenderId: "your credentials",
  appId: "your credentials"
};
Enter fullscreen mode Exit fullscreen mode

Let’s now start the Firebase service and enable the Google auth provider.

firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();
const provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({ prompt: "select_account" });
Enter fullscreen mode Exit fullscreen mode

We can now use the auth object to define our sign in and sign out functions.

const signIn = () => auth.signInWithPopup(provider);
const signOut = () => auth.signOut();
Enter fullscreen mode Exit fullscreen mode

When you call the **signIn **function, a popup will appear from which you can select your Google account. And the **signOut **function logs you out and clears the session. Isn’t it too simple? ;)

We must now keep track of whether or not the user is logged in. This will remain a state variable.

const [user, setUser] = useState(null);
Enter fullscreen mode Exit fullscreen mode

This object contains basic metadata about the logged in user, such as display name and email address.

We’ll then listen for auth changes from Firebase. This is required to check if the user is already logged in when you return or to update the state once you successfully login.

useEffect(() => {
  firebase.auth().onAuthStateChanged(async (user) => {
    setUser(user);
  });
}, []);
Enter fullscreen mode Exit fullscreen mode

You can also include any additional logic here. Sending the JWT token to your backend, for example, to keep session data, etc.

I’ll just paste the entire _app.js code we’ve written so far for reference.

import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import { useEffect, useState } from "react";

// Firebase config
const firebaseConfig = {
  apiKey: "your api key",
  authDomain: "your credentials",
  projectId: "your credentials",
  storageBucket: "your credentials",
  messagingSenderId: "your credentials",
  appId: "your credentials"
};

// Initialize firebase and google provider
firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();
const provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({ prompt: "select_account" });

// Sign in and sign out functins
const signIn = () => auth.signInWithPopup(provider);
const signOut = () => auth.signOut();

function MyApp({ Component, pageProps }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    firebase.auth().onAuthStateChanged(async (user) => {
      setUser(user);
    });
  }, []);

  return (
    <Component 
      {...pageProps} 
      user={user} 
      signIn={signIn} 
      signOut={signOut} 
    />
  );
}

export default MyApp;
Enter fullscreen mode Exit fullscreen mode

Step 5 : Fire it up!

To test the authentication, add some simple logic to the index.js file.

export default function Home(props) {
  return (
    <div>
      {props.user ? (
        <>
          <span>Signed in as : {props.user.email}</span>
          <button onClick={props.signOut}>Sign Out</button>
        </>
      ) : (
        <button onClick={props.signIn}>Sign In</button>
      )}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Start the project and see the results.

npm run dev
Enter fullscreen mode Exit fullscreen mode

That’s it!

You now have a Next.js project that uses Google authentication. If I missed anything, please let me know in the comments.

Cheers and happy coding!

Top comments (0)