Implementing User Authentication with Next JS and Firebase
Last Updated :
28 Apr, 2025
In this article, we are going to learn how we can use Firebase with Next JS to implement user authentication. So, that user can log in using their credentials or Google account. For this project, sound knowledge of Next JS and FIrebase is required. If you are new then, don't worry every step in this tutorial will be user-friendly. Get ready with your preferred IDE and log in to Firebase as it is free and advantageous for this project.
Output Preview: Let us have a look at how the final output will look like.
Sign up pagePrerequisites:
Approach to Implement User Authentication with NextJS and Firebase:
We are initially going to set up Firebase so that we can use it in our NextJS web application, then we will create a NextJS web application and connect Firebase with our web application. Firebase will be responsible for storing user's information and their credentials. Users can register themselves and later log in using their correct credentials.
Setting Up Firebase:
Let's start building our project and initially, we have to set up our Firebase.
Step 1: Create a new project: Go to the Firebase website and then log in with your Google account. After successful login, click on "Create a project".
Step 2: Name Your Project: On this page, you have to name your project it may be anything, your project your choice. After naming your project, click on continue and it will ask for Google Analytics you may turn it on if you want. Just choose your preferred setting and your project will be created successfully.
Step 3: Setting up Web Application: After reaching the main dashboard of Firebase, we have to create a web application so that, our application can authenticate users using their Gmail account.
For that, click on "web" on the dashboard, for adding firebase to our web application.
Step 4: Add Firebase to the Web App: Now, on this page, you have to give a name to your app and then we can use Firebase in our Web Application. After entering a name, click on "Register app".
After successfully registering our app, it will show SDK to use Firebase in our web application. The page will look like this and remember to use your credentials.
SDK Step 5: Choosing Authentication Type: Now we have to choose the authentication type so that our users can register themselves and authenticate. Here we are going to use "Email/password" because it will allow the user to enter their email and password. You can try other methods too but in this tutorial, we are going to use "email/password" authentication. Follow the below steps:-
- 1. Click on "Authentication"
- 2. Click on "Get Started"
- 3. Click on the "Email/Password" option from the options menu.
- 4. Click on "Enable" and then click on "Save"
- 5. Now to reaccess your SDK, Click on "project settings" -> "General" And scroll down you will see your all SDK information.
- Now we have set up our Firebase, it's time to create our web application using NextJS. We will use our SDK information in our web application to connect Firebase. So remember this crucial point.
Step to Create a Next JS Applcation:
Step 1: Setting up NextJS : First, create any directory in which we are going to install all our packages and components. Use vscode or any other IDE to install packages. Enter the below commands in the Vscode terminal to create a NextJS app.
npx create-next-app .
Then choose the following options as "yes" .
Creating NextJs applicationStep 2: Install the necessary package in your application using the following command.
npm install firebase
Project Structure:
Project StructureThe updated dependencies in package.json file will look like:
"dependencies": {
"firebase": "^10.8.0",
"next": "14.1.0",
"react": "^18",
"react-dom": "^18"
}
Example: Write the following code in respective files
JavaScript
// app/firebase/config.js
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import { getAuth } from 'firebase/auth'
const firebaseConfig = {
// Make sure to paste your own SDK here
//your own key
apiKey: "AIzaSyDLakJA2913lao5-coYdNsgYOmhUdmqqUQ",
authDomain: "cosmos-bc240.firebaseapp.com",
projectId: "cosmos-bc240",
storageBucket: "cosmos-bc240.appspot.com",
messagingSenderId: "419815671214",
appId: "1:419815671214:web:6f412f8affff60aaa6b43f",
measurementId: "G-8H6FHT4ZME"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
export const auth = getAuth(app);
export default function () { (<>Dummy function</>) }
JavaScript
// app/log-in/page.js
'use client'
import React from "react";
import { useRef } from "react"
import { auth } from '@/app/firebase/config';
import {
signInWithEmailAndPassword
} from "firebase/auth";
const login = () => {
const logemailRef = useRef();
const logpasswordRef = useRef();
const login = (e) => {
e.preventDefault();
const email = logemailRef.current.value;
const password = logpasswordRef.current.value;
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ...
console.log(user)
alert(`Welcome ${user.email}
redirecting to GeeksForGeeks`)
//router to next page
window.location.href =
'https://auth.geeksforgeeks.org/user/ujjwal_gupta';
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
alert(errorMessage)
});
}
return (
<div>
<center>
<h1>Log in screen</h1><br /><br />
<form onSubmit={login}>
<input type="email"
placeholder="Enter your email"
ref={logemailRef}
style={{ color: 'green' }} /><br />
<br></br>
<input type="password"
placeholder="Enter your password"
ref={logpasswordRef}
style={{ color: 'green' }} /><br />
<br /><button type="submit"
className="w-200 p-3 bg-indigo-600
rounded text-white hover:bg-indigo-500">
Log In
</button>
</form>
</center>
</div>
)
}
export default login
JavaScript
// app/sign-up/page.js
'use client'
import React from "react";
import { useRef } from 'react'
import {
createUserWithEmailAndPassword
} from "firebase/auth";
import { auth
} from '@/app/firebase/config';
import {
redirect
} from "next/dist/server/api-utils";
const signup = () => {
const emailRef = useRef();
const passwordRef = useRef();
const signup = (e) => {
e.preventDefault();
const email = emailRef.current.value;
const password = passwordRef.current.value;
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed up
const user = userCredential.user;
// ...
alert(`Successfully signup
redirecting to Log in page`);
window.location.href = './log-in/';
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
alert(errorMessage);
});
}
return (
<div>
<center>
<h1>Sign Up screen</h1><br /><br />
<form onSubmit={signup}>
<input type="email"
placeholder="Enter your email"
ref={emailRef}
style={{ color: 'green' }} />
<br /><br></br>
<input type="password"
placeholder="Enter your password"
ref={passwordRef}
style={{ color: 'green' }} /><br />
<br />
<button type="submit"
className="w-200 p-3 bg-indigo-600
rounded text-white hover:bg-indigo-500">
Sign Up
</button>
</form>
</center>
</div>
)
}
export default signup
Start your application using the following command.
npm run dev
Output: Now go to http://localhost:3000 and our web application is live and kicking.
Sign up page
Explanation of Output:
- we defined 'use client' because are using a client-side component, and we don't use this Nextjs won't run and throw errors at us.
- We imported some libraries and functions so that our web application could communicate efficiently.
- After successfully signing up, the user will be redirected to the login page.
- If some error occurs it will show the errors. Like password should be of length 6 or more.
- Again make sure to copy your own SDK and then paste it in the "firebaseConfig()".
Registered users on our web appConclusion
Working with NextJS is quite complicated because of its naming conventions, we have to make sure that we use correct and rule-based names in our web application or it will later, throw an error at us. Authentication with Firebase is pretty easy and requires some sound knowledge of NextJS and Tailwind to design our web application.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read