'Firebase Cloud Function config to access other project db

I need to create a Cloud Function that will access the Firebase DB that is running in another project. If it was accessing the db in the current project, I could use code such as

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

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

however, what I want is for functions.config().firebase to return the information (and, most importantly, credentials) for the other project. Is there any easy way to do this?



Solution 1:[1]

functions.config().firebase is a reserved namespace and you won't be able to override it. However, you can do cross-project initialization yourself. Here's how I would do it:

First, download a service account for your other project into your functions directory. Name it <project_id>-sa.json. Next, set up some environment config (app.other_project_id is just an example name, not a requirement):

firebase functions:config:set app.other_project_id="<the_project_id>"

Now in your code, you can initialize the Admin SDK like so:

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

if (!functions.config().app || !functions.config().app.other_project_id) {
  throw new Error('Cannot start app without app.other_project_id config.');
}

const FB_PROJECT_ID = functions.config().app.other_project_id;
const SERVICE_ACCOUNT = require(`./${FB_PROJECT_ID}-sa.json`);

admin.initializeApp({
  databaseURL: `https://${FB_PROJECT_ID}.firebaseio.com`,
  credential: admin.credential.cert(SERVICE_ACCOUNT)
});

This will have initialized the Admin SDK for the other project.

Solution 2:[2]

instead of

if (!functions.config().app || !functions.config().app.project_id) {

You should use

if (!functions.config().app || !functions.config().app.fb_project_id) {

NOTE: the typo in project_id

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AKd
Solution 2 Robert Mengual