Integrating Real-time Database and Authentication using Next JS and Firebase

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 Structure

Example: 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/



Contact Us