How to get Firebase Project Name or ID from Cloud Function

Viewed 16810

I am using Cloud Functions and want to get the project name from within one of my Javascript server files. I know that value is stored in the .firebaserc, but I don't think that file is available on the server, right? I want to do something like this:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.getProjectName();  // or getProjectID()

or

functions.getProjectName(); 
10 Answers

Firebase admin SDK has access to that information for you.

const admin = require('firebase-admin');
const projectId = admin.instanceId().app.options.projectId

This worked for me. (node 10)

const FIREBASE_CONFIG = process.env.FIREBASE_CONFIG && JSON.parse(process.env.FIREBASE_CONFIG);
const projectId = FIREBASE_CONFIG.projectId;

try this :

const projectId = admin.instanceId().app['options_'].credential.projectId

For cloud functions running on newer versions of Node:

import firestore from "@google-cloud/firestore";

const client = new firestore.v1.FirestoreAdminClient();
const projectId = await client.getProjectId();

From the Firebase docs:

process.env.FIREBASE_CONFIG: Provides the following Firebase project config info:

{
  databaseURL: 'https://databaseName.firebaseio.com',
  storageBucket: 'projectId.appspot.com',
  projectId: 'projectId'
}

Note that since it's a JSON string you need to parse it like this:

const projectId = JSON.parse(process.env.FIREBASE_CONFIG).projectId;

Alternatively you could use the undocumented firebaseConfig() method from the firebase-functions package in your Cloud Functions, like so:

import { firebaseConfig } from "firebase-functions";
const projectId = firebaseConfig().projectId;

Additionally, Google Cloud Platform (which Firebase runs on top of) will automatically populate the environment variables documented here, depending on which runtime you're using.

The way to retrieve the project ID using admin SDK is

admin.appCheck().app.options.credential.projectId

This also works in headless setups like Docker where the environment variable GOOGLE_APPLICATION_CREDENTIALS is set.

Currently I'm using app.INTERNAL.credential_.projectId. This is clearly not save, but so far there is no cohesive way to get it (AFAIK)

This is a combination of the answers given above:

function getProjectID() {
  return firebaseInstance.options.projectId ||
    (firebaseInstance.options.credential && firebaseInstance.options.credential.projectId) || '';
}

Or in TypeScript:

function getProjectID(): string {
  return firebaseInstance.options.projectId ||
    (firebaseInstance.options.credential && (firebaseInstance.options.credential as unknown as { projectId: string }).projectId) || '';
}

You can use functions.config().firebase.projectId

PS the easiest way to initialize app is admin.initializeApp(functions.config().firebase);

Related