Paul de Wit
Paul de Wit

Reputation: 587

Create multiple instances of firebase-admin

I have multiple Firebase databases, and I would like to create one admin which connects to all databases. To initialize the app I first require the Firebase-admin module and initialize the app. If I run this again with different credentials it will still only initialize the one app.

var admin = require("firebase-admin");
...


Object.keys(config).map(function (k, i){

var c = config[k];

var serviceAccount = require(c.credential);

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    apiKey: c.apiKey,
    authDomain: c.authDomain,
    databaseURL: c.databaseURL,
    storageBucket: c.storageBucket
}, c.name);
...
}

This does not work! Only one app is initialized even though there are two configurations.

Upvotes: 19

Views: 11973

Answers (3)

manufosela
manufosela

Reputation: 518

With firebase 9:

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

const mainServiceAccount = require('./path/to/main/serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(mainServiceAccount),
  databaseURL: 'https://<MAIN_DATABASE_NAME>.firebaseio.com'
});

const secondaryAdmin = require('./path/to/secondary/serviceAccountKey.json');
const secondaryAppConfig = {
    credential: admin.credential.cert(secondaryServiceAccount),
    databaseURL: 'https://<SECONDARY_DATABASE_NAME>.firebaseio.com'
};
const secondary = initializeApp(secondaryAdmin, 'secondary');

const ref1 = admin.database().ref(path);

const ref2 = secondary.database().ref(path2);

Upvotes: 2

jwngr
jwngr

Reputation: 4422

// Initialize the default app
firebase.initializeApp(defaultAppConfig);

// Initialize another app with a different config
var otherApp = firebase.initializeApp(otherAppConfig, "other");

console.log(defaultApp.name);  // "[DEFAULT]"
console.log(otherApp.name);    // "other"

// Use the shorthand notation to retrieve the default app's services
var defaultAuth = firebase.auth();
var defaultDatabase = firebase.database();

// Use the otherApp variable to retrieve the other app's services
var otherAuth = otherApp.auth();
var otherDatabase = otherApp.database();

Check out the Initialize mutltiple apps docs of the Firebase Admin SDK setup guide for more details.

Upvotes: 30

Paul de Wit
Paul de Wit

Reputation: 587

Figured it out...

var app = admin.initializeApp({... })

var db = admin.database(app);

Upvotes: 8

Related Questions