Using Firebase with Next.js

July 19, 2019 (5y ago)

đŸ’¡

This post has been updated for the Next.js 13 app directory.

This guide will show you how to use Firebase 9+ with Next.js and deploy it to Vercel.

Connecting to Firebase

  1. Create a project in Firebase.
  2. In the Firebase console, open Settings > Service Accounts.
  3. Click Generate New Private Key, then confirm by clicking Generate Key.
  4. Download and open the JSON file containing your service account.
  5. Create a new file .env.local and add environment variables with those values.
NEXT_PUBLIC_FIREBASE_PROJECT_ID=replace-me
FIREBASE_CLIENT_EMAIL=replace-me
FIREBASE_PRIVATE_KEY=replace-me

You can now fetch data from Firebase directly inside a Server Component in the app directory:

import 'server-only';
import { notFound } from 'next/navigation';
import * as admin from 'firebase-admin';

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

const db = admin.firestore();

export default async function Page() {
  const user = await db.collection('users').doc('leerob').get();

  if (!user.exists) {
    notFound();
  }

  return <div>Hello, {user.data().name}!</div>;
}

Since all components used inside the app directory are Server Components by default, they are only executed on the server. This means you can safely use environment variables without exposing them to the client.

For added security and peace of mind, the page is marked as server-only.

Conclusion