Implementing User Authentication with Next JS and Firebase
Last Updated :
23 Jul, 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://www.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
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
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. Why Use React?Before React, web development faced issues like slow DOM updates and mes
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides methods to interact with the Document Object Model, or DOM. This package allows developers to access and modify the DOM. It is a package in React that provides DOM-specific methods that can be used at the top level of a web app to enable an efficient wa
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.Stateless (before hooks)
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects