In this tutorial, we’ll learn how to add Firebase authentication to a Next.js app. We’ll use Firebase’s authentication service to create a login page with Google authentication.
Contents
Prerequisites
pnpm
installed globally - you still can use npm or yarn but make sure to replacepnpm
withnpm
oryarn
accordingly
The first thing is to create a Next.js app. I’m going to create one app using the following command.
pnpm create next-app
Adding Firebase
After creating the app, we need to create a Firebase project. Go to the Firebase console and create a new project. After creating it, you should be able to see the project dashboard.
Now, go to Build > Authentication and enable the Google sign-in method. You can enable other sign-in methods as well. But, for this tutorial, we will only use the Google sign-in method.
Nice! Now, we need to create a Firebase app. Go to Project settings > General and click on the </>
icon to add a new app.
Now, you should be able to see the Firebase SDK snippet. Go to the Next.js app and create a new file called firebaseConfig.js
in the root directory. Copy the Firebase SDK snippet and paste it into the firebaseConfig.js
file. And then, export the config by adding the following code to the firebaseConfig.js
file.
After that, install the Firebase SDK for the Web using the following command.
pnpm install firebase
We now have the Firebase SDK installed. The next thing is to add authentication to the app.
Adding authentication
Go to the firebaseConfig.js
file and add the following code.
Open the app by running the following command.
pnpm run dev
Let’s edit the pages/index.js
file and add the following code.
We have a minimal UI.
We now add the sign-in functionality. Go to the pages/index.js
file and add replace the code with the following code.
We have added the signInWithGoogle
function. Now, we need to add the onClick
event to the button. We also added a pre
tag to display the debug info.
Try clicking the button. You should be able to see the following.
After signing in, you should be able to see the user object in the debug info.
We can use that user object to get the user’s name, email, and profile picture.
And that’s it! We have successfully added authentication to a Next.js app using Firebase.
Conclusion
In this tutorial, we learned how to add authentication to a Next.js app using Firebase. We also learned how to get the user’s name, email, and profile picture. The code for this tutorial is available on GitHub.
Connect with me