Firebase with Next.js

Integrating Firebase with Next.js allows you to build powerful full-stack applications with ease. However, you must decide what runs on the client vs. the server.

1. Client-side vs. Server-side

  • Client-side: Use the standard Firebase Web SDK. Perfect for real-time updates and simple auth.
  • Server-side: Use firebase-admin. Required for SSR (Server Side Rendering) and API routes.

2. Using Firebase Admin (Server-only)

// lib/firebaseAdmin.js
import admin from "firebase-admin";

if (!admin.apps.length) {
  admin.initializeApp({
    credential: admin.credential.cert({
       projectId: process.env.FIREBASE_PROJECT_ID,
       clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
       privateKey: process.env.FIREBASE_PRIVATE_KEY.replace(/\n/g, "\n"),
    }),
  });
}

export const db = admin.firestore();

3. Simple SSR Example

export async function getServerSideProps() {
  const snapshot = await db.collection('posts').get();
  const posts = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
  return { props: { posts } };
}

4. Environment Variables

Crucial! Store your credentials in .env.local.

NEXT_PUBLIC_FIREBASE_API_KEY=...
FIREBASE_PRIVATE_KEY="..."
Check out: next-firebase-auth-edge is a popular library for managing Firebase Auth across the edge in Next.js.