Initialize the Firebase Admin with Next.js

Learn how to use Firebase on the server with Next.js

ยท2 min read

The Firebase Admin package is a way to use Firebase on NodeJS, thus allowing us to write backend code with the various Firebase packages such as Auth, Firestore, Storage, and so on.

To use Firebase with a Next.js API function, we have to initialize the Firebase Admin. Let's see how it's done:

Firebase configuration

First, we have to store and retrieve the Firebase configuration for our project.

To do so, we can use the Next.js environment variables by creating a .env file in the root folder, and making sure to fill the values below correctly:

NEXT_PUBLIC_FIREBASE_PROJECT_ID=
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=
FIREBASE_PRIVATE_KEY=
FIREBASE_CLIENT_EMAIL=

Once it's done, we can create a function that accepts the following interface and returns the Firebase admin app:

interface FirebaseAdminAppParams {
  projectId: string;
  clientEmail: string;
  storageBucket: string;
  privateKey: string;
}

The snippet below is everything you need to create an admin app using Firebase:

import admin from 'firebase-admin';

function formatFirebasePrivateKey(key: string) {
  return key.replace(/\\n/g, '\n');
}

export function createFirebaseAdminApp(params: FirebaseAdminAppParams) {
  const privateKey = formatFirebasePrivateKey(params.privateKey);
  
  // if already created, return the same instance
  if (admin.apps.length > 0) {
    return admin.app();
  }

  // create certificate
  const cert = admin.credential.cert({
    projectId: params.projectId,
    clientEmail: params.clientEmail,
    privateKey,
  });

  // initialize admin app
  return admin.initializeApp({
    credential: cert,
    projectId: params.projectId,
    storageBucket: params.storageBucket,
  });
}

Let's assume you created a Next.js API function and want to create a Firebase admin app to be able to use Firestore, you can do the following:

import { createFirebaseAdminApp } from './initialize-firebase-admin-app';
import { getFirestore } from 'firebase-admin/firestore';

async function initializeAdmin() {
  const params = {
    projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
    clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
    storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
    privateKey: process.env.FIREBASE_PRIVATE_KEY
  };

  return createFirebaseAdminApp(params);
}

export default function getTeams(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  // initialize admin
  await initializeAdmin();

  // now we can use the Firebase packages!
  const firestore = getFirestore();

  const { docs, size } = await firestore.collection('teams').get();
  const teams = docs.map(doc => doc.data())

  return res.send(teams);
}

Stay informed with our latest resources for building a SaaS

Subscribe to our newsletter to receive updatesor