DEV Community

Cover image for Google oAuth on NextJs
Ekama Emmanuel
Ekama Emmanuel

Posted on

Google oAuth on NextJs

If your search has brought you here, then I'm sure you have done some type of authentication and authorization with probably Express PassportJs on a project, so Let's save our time by jumping to straight to bullet overview and implementation.

Overview
  • Add NextJs app to Google console
  • Configure NextJs app with firebaseConfig (some few changes with firebase v9.0.0)
  • Employ environment variable to hold secret
  • Build an auth-Service
  • Protected routes with custom hooks

Adding your Next app to Google console is pretty easy, It's like when you deploy on Varcel, with some few clicks you are done! You have a dashboard that gives a brief overview of your project when you create a project on google console. click on "Add app" button at the top and you will be taken to this page to provide a nickname for your app, mine is MetaApp. Then, follow the next few steps, it is self explanatory. Don't forget to copy firebaseConfig!

Register app

Now you're through with app registration, let's make use of the snippet you copied. Create a file with a name related to firebase, something like fireBaseClient.js in a Service Folder and then import firebase app and auth. *side note **We import app and auth from *firebase/compact/ not firebase/ since Version 9 like so

// service/fireBaseClient.js

import firebase from "firebase/compat/app";    firebase v9
import "firebase/compat/auth";                 firebase V9
import "firebase/compat/firestore";            firebase V9

// import firebase from "firebase/app";         firebase v8 
// import "firebase/auth";                      firebase v8 
// import "firebase/firestore";                 firebase v8 



const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
  measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
};
if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}
export default firebase;
Enter fullscreen mode Exit fullscreen mode

You noticed how we hid the secret keys with environment variable? yeah, it's possible with NextJs. All I did was add an env.local file to the root directory and paste the secret. Another side note is that each env variable should start with NEXT_PUBLIC_ with whatever you chose to complete the name. It's how Next.js gets to know what to load or bundle. Also, there are trailing commas , that came with the code we copied, get rid of them. I lost a couple hours debugging them. Once that is done we don't have to worry about our secret getting stolen by village people, haha! Quick example

NEXT_PUBLIC_SOMENAME = "MetaAppSecrete"
// don't forget the comma
Enter fullscreen mode Exit fullscreen mode

You will also see a condition !firebase.apps.length, this is to make sure we don't initialize another firebase app. Now we have completed firebase setup. It's time to build a signUpWithGoogle service

service/firebaseAuth.service.js

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

export const  AuthService = {}

AuthService.loginWithGoogle = async () => {
  const provider = new firebase.auth.GoogleAuthProvider();
  try {
    const { user } = await firebase.auth().signInWithPopup(provider);
    return {
      user,
    };
  } catch (error) {
    return {
      error: error.message,
    };
  }
};


AuthService.logout = async () => {
  await firebase.auth().signOut();
};
Enter fullscreen mode Exit fullscreen mode

Honestly, I feel like there is no need explaining the code because you might shoplift it, which in my opinion, is the best technique of coding fast with StackOverflow. But let me explain, google gives us a provider when we execute this new firebase.auth.GoogleAuthProvider() and we will call the type of login method we want on the provider, in our case it's signInWithPopup type. There are others that redirects the user but I prefer the popup.

Finally, we can tie our loginWithGoogle function to a signup button with an onClick event. You don't need a snippet for this, do you?

This post is becoming too long so I will deal with route protection in as a separate post.

Top comments (0)