This guide will show you how to utilize two separate firebase projects in one admin application.

The code

import 'firebase';
import * as admin from 'firebase-admin';
import serviceAccountOne from 'path/to/service-account-1';
import serviceAccountTwo from 'path/to/service-account-2';

const app_one = admin.initializeApp({
  credential: admin.credential.cert(serviceAccountOne),
  databaseURL: 'https://<1st-db-name>.firebaseio.com'
}, 'appOne');

const app_two = admin.initializeApp({
  credential: admin.credential.cert(serviceAccountTwo),
  databaseURL: 'https://<2nd-db-name>.firebaseio.com'
}, 'appTwo);

export const appOne = app_one;
export const appTwo = app_two;

Part 1 - Import

The import part. There are four files that we need to import, firebase, firebase-admin, and the two service account files.

These are all essential to achieve our goal. Notice that there two different service accounts, this means that you have to generate them separately from the dashboard of each firebase projects.

Part 2 - Initialization

In order for use to use firebase from the backend, we need to of course initialize the app. This is just the same initialization that we all know when using firebase admin sdk, expect that you will notice there's a 2nd argument to the .initializeApp method.

The 2nd argument is the namespace or the the name that you want to call your application. By default, the namespace is "default". You don't have to supply this argument if you are using firebase with only one application instance.

Syntax

.initializeApp([options, [namespace]])

Part 3 - Export

After the initialization you now have two separate instance of firebase apps. You need to export those instances like so:

export const appOne = app_one;
export const appTwo = app_two;

Part 4 - Consumption

To use the instances just import the instances like:

import { appOne, appTwo } from '../path/to/the/file/above';

And finally use it like:

appOne.database();
appTwo.database();