Firebase - How to connect to multiple Firebase projects at the same time?

This is a rare situation, but the good news is it's doable and it's very easy.

Firebase - How to connect to multiple Firebase projects at the same time?
Photo by Ben Moreland / Unsplash

This is a rare situation, but the good news is it's doable and it's very easy.

Prerequisites

  • 2 Firebase accounts
  • That's it!

Install Firebase and Firebase Admin

yarn add firebase firebase-admin

Import Firebase and Service Accounts

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

Here we are importing, firebase, firebase-admin, and the service account credentials for our multiple firebase instances.

Initialize the first Firebase app instance

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

Here, we are passing two arguments to the .initializeApp method. The first one is the configuration object which contains the credentials (the service account credentials), and the databaseURL. The second argument is the app name, this is because this argument will determine the name of this unique instance. You can name it whatever you want as long as it's different from the other instances that you will initialize.

Initialize the second Firebase app instance

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

We will repeat what we did in the previous step.

Export the Firebase app instances

export const first = firstApp;
export const second = secondApp;

Here we are just doing a named export to export the instances we just created.

Final script

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

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

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

export const first = firstApp;
export const second = secondApp;

It's very short and clean isn't it?

Usage

import { first, second } from '../path/to/the/file/above'
 
first.database();
second.database();

Now you can access both instances and do whatever cool stuff you are doing! Happy coding!