Deploying Firebase App with Service Account to Heroku (environment variables with dotenv)

There's two three mandatory fields for the cert options object: clientEmail and privateKey (and now also projectId). Your example can be trimmed down to:

admin.initializeApp({
  credential: admin.credential.cert({
    "projectId": process.env.FIREBASE_PROJECT_ID
    "private_key": process.env.FIREBASE_PRIVATE_KEY,
    "client_email": process.env.FIREBASE_CLIENT_EMAIL,
  }),
  databaseURL: "https://my-firebase-app.firebaseio.com"
});

As an aside, some environments might have trouble with newlines in the private_key env var; I found key.replace(/\\n/g, '\n') to be a straightforward solution.


  1. Convert the firebase config JSON (serviceAccountKey) to base64 encoded string, this can be done in many ways like using openssl command openssl base64 -in <firebaseConfig.json> -out <firebaseConfigBase64.txt> or using Nodejs as illustrated below
Buffer.from(JSON.stringify({
  "type": "",
  "project_id": "",
  "private_key_id": "",
  "private_key": "",
  "client_email": "",
  "client_id": "",
  "auth_uri": "",
  "token_uri": "",
  "auth_provider_x509_cert_url": "",
  "client_x509_cert_url": ""
})).toString('base64')
  1. Save the output base64 encoded string of the above step in an env variable like GOOGLE_CONFIG_BASE64. (Save it to ConfigVars in case of Heroku)
  2. Initialise the firebaseSdk in your node application
const firebaseAdminSdk = require('firebase-admin'),
    firebaseAdminApp = firebaseAdminSdk.initializeApp({credential: firebaseAdminSdk.credential.cert(
      JSON.parse(Buffer.from(process.env.GOOGLE_CONFIG_BASE64, 'base64').toString('ascii')))
});