Integrating Real-time Database and Authentication using Next JS and Firebase
Last Updated :
13 Jun, 2024
NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. In this article, we will learn how to integrate Firebase's real-time database and authentication using Next.js.
Prerequisites
Steps to setup Firebase Web Project
Step 1: Sign in to Firebase
- Go to the Firebase Console.
- Sign in with your Google account.
Step 2: Create a New Project
- Click on the Add project button.
- Enter a project name and accept the Firebase terms and conditions.
- Click on Create project and wait for the project to be created.
Step 3: Add a Web App to the Project
- In the Firebase Console, go to the Project Overview.
- Click on the web icon (</>)
- Register your app by entering an app nickname (this is optional for your reference).
Step 4: Get the Firebase SDK Configuration
- After registering your app, Firebase will provide you with a Firebase SDK snippet.
- This configuration object contains keys and identifiers required to connect your web app to Firebase services.
Copy the configuration code snippet. It looks something like this:
import { initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_PROJECT_ID.appspot.com",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID",
measurementId: "YOUR_MEASUREMENT_ID"
};
const app = initializeApp(firebaseConfig);
Step 5: Authentication Setup
- In a side panel, you will find a Product categories. Click on Build section.
- Select the Authentication, then click on Get Started button.
- In Sign In Method section, In Native providers, select "Email/Password".
- Enable Email/Password and Click on Save button.
- In Users tab, all the registered users will be displayed there.
Next.js Application Setup
Step 1: Create a NextJS application using the following command and answer a few questions.
npx create-next-app@latest app_name
Step 2: It will ask you some questions, so choose as the following.
√ Would you like to use TypeScript? ... No
√ Would you like to use ESLint? ... Yes
√ Would you like to use Tailwind CSS? ... No
√ Would you like to use `src/` directory? ... Yes
√ Would you like to use App Router? ... Yes
√ Would you like to customize the default import alias (@/*)? ... No
Step 3: After creating your project folder, move to it using the following command.
cd app_name
Step 4: Install Firebase using the following command:
npm i firebase
The updated dependencies in pakage.json will look like this:
"dependencies": {
"firebase": "^10.12.2",
"next": "14.2.3",
"react": "^18",
"react-dom": "^18"
},
Project Structure:
Folder StructureExample: The below example demonstrate the integration of firebase with Next.js application.
JavaScript
//File path: src/app/firebaseConfig.js
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth"
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_PROJECT_ID.appspot.com",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID",
measurementId: "YOUR_MEASUREMENT_ID"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app)
export default auth;
JavaScript
//File path: src/app/layout.js
import Link from "next/link"
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<ul style={{ display:"flex", margin:0, padding:0,
gap:"10px", listStyle:"none"}}>
<li><Link href={'/'}>Register</Link></li>
<li><Link href={'/login'}>Login</Link></li>
</ul>
{children}
</body>
</html>
);
}
JavaScript
//File path: src/app/page.js
'use client';
import { useState } from 'react';
import auth from './firebaseConfig';
import { createUserWithEmailAndPassword } from 'firebase/auth';
import { useRouter } from 'next/navigation';
export default function Home() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const router = useRouter()
const registerUser = async () => {
try
{
const user = await createUserWithEmailAndPassword(auth, email, password);
if (user._tokenResponse) {
alert("Registered Successfully")
return router.push("/welcome")
} else {
return alert("Please Try Again")
}
} catch (error) {
return alert(error.message);
}
}
return (
<>
<h1>Register</h1>
<input type="email" placeholder="Enter Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<br/><br/>
<input type="password" placeholder="Enter Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<br/><br/>
<button onClick={registerUser}>Register</button>
</>
);
}
JavaScript
//File path: src/app/welcome/page.js
'use client';
import { useRouter } from 'next/navigation';
import auth from '../firebaseConfig';
import { signOut } from 'firebase/auth';
export default function Page() {
const router = useRouter()
const signout = async () => {
await signOut(auth)
alert("Sign out Successfully")
return router.push('/login')
}
return (
<>
<h1>Welcome {auth.currentUser?.email}</h1>
<button onClick={signout}>Logout</button>
</>
)
}
JavaScript
//File path: src/app/login/page.js
'use client';
import { useState } from 'react';
import auth from '../firebaseConfig';
import { signInWithEmailAndPassword } from 'firebase/auth';
import { useRouter } from 'next/navigation';
export default function Home() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const router = useRouter();
const login = async () => {
try {
const user = await signInWithEmailAndPassword(auth, email, password);
if (user._tokenResponse) {
alert("Login Successfully")
return router.push("/welcome")
} else {
return alert("Please Try Again")
}
} catch (error) {
return alert(error.message);
}
}
return (
<>
<h1>Login Page</h1>
<input type="text" placeholder="Enter Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<br /><br />
<input type="password" placeholder="Enter Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<br /><br />
<button onClick={login}>Login</button>
</>
);
}
Step to Run Application: Run the application using the following command from the root directory of the project
npm run dev
Output: Your project will be shown in the URL http://localhost:3000/
Similar Reads
Firebase Realtime Database: Reading and Writing Data
Firebase Realtime Database, a cloud-hosted NoSQL database developed by Google, provides a robust solution for achieving seamless real-time data updates across connected clients. In this article, We will learn about the Firebase Realtime Database, How to Setting Up the Firebase Realtime Database, wri
7 min read
Implementing User Authentication with Next JS and Firebase
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
6 min read
Anonymous authentication in firebase using React JS
This method explains how to sign in without revealing your identity using Firebase in a React app. It's like having a secret entry you create and use temporary anonymous accounts for logging in. We make it happen by using the special tools provided by Firebase. Prerequisites:React JSFirebaseApproach
3 min read
How to push data into firebase Realtime Database using ReactJS ?
Firebase is a popular backend-as-a-service platform that provides various services for building web and mobile applications. One of its key features is the Realtime Database, which allows developers to store and sync data in real-time. In this article, we will explore how to push data into the Fireb
2 min read
User Authentication and CRUD Operation with Firebase Cloud Firestore Database in Flutter
Google Firebase is an integrated service that uses all the facilities the backend can provide. In traditional app development/web development, the application's front end is connected to a server (also a computer device) in which the authentication program, database program, metadata of the program,
6 min read
Google Signing using Firebase Authentication in Android
Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides email and password authentication without any overhead of building the backend for user authentication. Google Sign-In is a secure way to
8 min read
How to get current date and time in firebase using ReactJS ?
This article provides a detailed walkthrough on obtaining the current date and time in a Firebase environment using ReactJS. Readers will gain insights into the implementation process, enabling date and time functionalities into their React projects powered by Firebase. Prerequisites:Node JS or NPMR
2 min read
Firebase (sign in with Google) Authentication in Node.js using Firebase UI and Cookie Sessions
Firebase Authentication provides the backend services that are easy-to-use SDKs and ready-made UI libraries to authenticate users to your app. Prerequisites: Basic knowledge of node, JavaScript and firebase. Setup: First we need to create a Firebase Project, head over to firebase Console and create
4 min read
Data Organization in Firebase Realtime Database
Firebase Realtime Database is a powerful tool that allows us to store and synchronize data in real-time across all clients. However, organizing data effectively in Firebase Realtime Database can be challenging for beginners. Proper data organization is important for efficient data retrieval, minimiz
7 min read
Setting Up and Configuring Firebase Realtime Database
Firebase Realtime Database is a cloud-hosted NoSQL database that allows us to store and sync data between our users in real-time. It is a powerful tool for building applications that require live updates, such as chat apps, collaborative tools, and real-time analytics. In this article, we will learn
6 min read