Me on my way to Death Valley (April 2023)

Firebase credentials in node.js

Michal Wrzosek

--

By default, Google is pushing developers to authenticate to Google Cloud using a JSON file that they provide. They want you to upload this file along with the app and provide the path to it to Firebase initializer. Often this is very uncomfortable and it is in my opinion more common to provide necessary secrets purely through environment variables.

Every time I set up a project with Firebase or Google Cloud services I ponder how to plug in all the secrets through envs — this is how to do this in a gist:

First, you take the contents of the secret JSON file that Google gave you (in Firebase Console => Project settings => Service accounts => Generate new private key), stringify it, and convert it to Base64:

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": "...",
"universe_domain": "..."
})).toString('base64')

You take the output string and plug it in as an environment variable, for example to your .env file:

GOOGLE_CLOUD_CREDENTIALS="..."

Then in your project, you can decypher this secret and initialize your app with it, for example like this:

import { credential } from 'firebase-admin';
import { AppOptions, getApps, initializeApp } from 'firebase-admin/app';

const GOOGLE_CLOUD_CREDENTIALS = JSON.parse(
Buffer.from(process.env.GOOGLE_CLOUD_CREDENTIALS!, 'base64').toString('utf-8')
);

const firebaseConfig: AppOptions = {
credential: credential.cert(GOOGLE_CLOUD_CREDENTIALS),
projectId: '...',
storageBucket: '....appspot.com',
};

const alreadyCreatedAps = getApps();

const app =
alreadyCreatedAps.length === 0
? initializeApp(firebaseConfig)
: alreadyCreatedAps[0];

As you can see, it all revolves around this trick with credential.cert().

--

--

Michal Wrzosek

Senior Software Engineer currently on contract assignment @ Shell in Rotterdam, Netherlands