Integrating Next.js with Firebase

Integrating Next.js with Firebase

·

3 min read

Firebase is a powerful backend-as-a-service platform that offers authentication, real-time databases, and hosting. Integrating Firebase with a Next.js application allows you to build scalable and serverless web applications with ease.


Why Use Firebase with Next.js?

  • Authentication: Secure user authentication with Firebase Auth.

  • Realtime Database & Firestore: Sync data across clients instantly.

  • Hosting: Deploy your Next.js app seamlessly using Firebase Hosting.

  • Serverless Functions: Extend backend logic with Firebase Cloud Functions.


Setting Up Firebase in Next.js

Step 1: Create a Firebase Project

  1. Go to Firebase Console.

  2. Click Add Project and follow the setup steps.

  3. Once created, go to Project Settings and get your Firebase credentials.

Step 2: Install Firebase SDK

Navigate to your Next.js project and install Firebase:

npm install firebase

Step 3: Configure Firebase

Create a firebaseConfig.ts file inside the lib/ folder:

// lib/firebaseConfig.ts
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};

const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
export const db = getFirestore(app);

Add the environment variables in .env.local:

NEXT_PUBLIC_FIREBASE_API_KEY=your-api-key
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your-auth-domain
NEXT_PUBLIC_FIREBASE_PROJECT_ID=your-project-id
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=your-storage-bucket
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=your-messaging-sender-id
NEXT_PUBLIC_FIREBASE_APP_ID=your-app-id

Implementing Firebase Authentication

Step 4: Create a Login Component

Create a simple authentication component using Firebase Auth:

// components/Login.tsx
import { useState } from "react";
import { auth } from "../lib/firebaseConfig";
import { signInWithEmailAndPassword, signOut } from "firebase/auth";

export default function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const handleLogin = async () => {
    try {
      await signInWithEmailAndPassword(auth, email, password);
      alert("Logged in successfully");
    } catch (error) {
      console.error("Error logging in:", error);
    }
  };

  const handleLogout = async () => {
    await signOut(auth);
    alert("Logged out");
  };

  return (
    <div>
      <input type="email" placeholder="Email" onChange={(e) => setEmail(e.target.value)} />
      <input type="password" placeholder="Password" onChange={(e) => setPassword(e.target.value)} />
      <button onClick={handleLogin}>Login</button>
      <button onClick={handleLogout}>Logout</button>
    </div>
  );
}

Step 5: Protect Routes Using Middleware

To restrict access to authenticated users, use Next.js middleware:

// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(req: NextRequest) {
  const token = req.cookies.get("auth-token");
  if (!token) {
    return NextResponse.redirect(new URL("/login", req.url));
  }
  return NextResponse.next();
}

export const config = {
  matcher: "/dashboard/:path*",
};

Deploying Next.js with Firebase Hosting

Step 6: Install Firebase CLI

If you haven’t installed Firebase CLI, run:

npm install -g firebase-tools

Login and initialize Firebase in your project:

firebase login
firebase init hosting

Choose:

  • Use an existing project (Select your Firebase project)

  • Build directory: .next

  • Configure as a single-page app: No

  • Set up automatic builds: No

Step 7: Deploy

Build your Next.js app and deploy it:

npm run build
firebase deploy

Conclusion

Integrating Firebase with Next.js enables seamless authentication, database management, and hosting. With Firebase’s real-time capabilities and serverless infrastructure, you can build scalable web applications efficiently. Try Firebase to enhance your Next.js project with powerful backend functionalities!

For more details, check out the official documentation: