How to initialize firebase admin using modular Firebase v9?

Viewed 1329

I'm using firebase admin to interact with Firestore and auth from a custom backend (next.js api routes).

Firebase recently announced they're going with modular tree-shaking packages.

How can I refactor below code to utilize tree-shaking firebase module?

import * as firebaseAdmin from "firebase-admin";

if (!firebaseAdmin.apps.length) {
  const adminCredentials = {
    credential: firebaseAdmin.credential.cert({
      projectId: env.fbProjIdPublic,
      clientEmail: env.fbClientEmail,
      privateKey: JSON.parse(env.fbPvtKey),
    }),
    databaseURL: env.fbDbUrlPublic,
  };

  firebaseAdmin.initializeApp(adminCredentials);
}

export default firebaseAdmin;

So far I couldn't find replacement for firebaseAdmin.credential.cert.

2 Answers

The documentation you linked is for the Web/JavaScript SDK, not for the Node.js Admin SDKs.

A modular Admin SDK for Node.js is under development, but not generally available yet. You can find the latest information and how to join the alpha program here.

You can also track its progress on the Github repo, like on this recent feature request, and this request for feedback from the engineers working on it.

I've tried and this works.

Env variables not being strings was my problem on local

import { initializeApp, App, AppOptions, getApps, getApp, cert } from "firebase-admin/app";


const clientEmail = process.env.FIREBASE_CLIENT_EMAIL;
const privateKey = process.env.FIREBASE_PRIVATE_KEY;
const projectId = process.env.FIREBASE_PROJECT_ID;

const firebaseAdminConfig: AppOptions = {
  credential: cert({
    clientEmail,
    privateKey,
    projectId,
  }),
};
Related