Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically switch to different firebase project databases (Javascript)

I need to develop an aggregate admin web app that needs to connect to different firebase project databases(of different google accounts).Is it possible to switch to different firebase project databases dynamically via javascript ?

like image 420
Sobinscott Avatar asked Apr 30 '18 09:04

Sobinscott


2 Answers

To access a dynamically determined database in your code, set the configuration data for the project that the database is hosted in.

var config = {
    apiKey: "<API_KEY>",
    authDomain: "<PROJECT_ID>.firebaseapp.com",
    databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
    storageBucket: "<BUCKET>.appspot.com",
};

var database = firebase.database();

var secondaryAppConfig = {
    apiKey: "<ANOTHER_API_KEY>",
    authDomain: "<ANOTHER_PROJECT_ID>.firebaseapp.com",
    databaseURL: "https://<ANOTHER_DATABASE_NAME>.firebaseio.com",
    storageBucket: "<ANOTHER_BUCKET>.appspot.com",
};

// Initialize another app with a different config
var secondary = firebase.initializeApp(secondaryAppConfig, "secondary");

// Retrieve the database.
var secondaryDatabase = secondary.database();

And now choose based on some condition that is specific to your app:

var db = my_condition ? database : secondaryDatabase;

See the sample in the Firebase documentation.

like image 65
Frank van Puffelen Avatar answered Sep 28 '22 02:09

Frank van Puffelen


@Puf has given the best answer. I will just add one point here. More of a security measure incase you are loading it in a browser there is chance that all your configs might be getting exposed.

I assume you have the liberty to create a new firebase called Router (or whatever you want to) and make the user signin(auth) to that first by default. Then based on a condition, send the config for the environment needed for that particular user.

eg:
{
    "env":{
       "e1":{
          apiKey: "<API_KEY>",
          authDomain: "<PROJECT_ID>.firebaseapp.com",
          databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
          storageBucket: "<BUCKET>.appspot.com"
       },
       "e2":{
          apiKey: "<API_KEY2>",
          authDomain: "<PROJECT_ID2>.firebaseapp.com",
          databaseURL: "https://<DATABASE_NAME2>.firebaseio.com",
          storageBucket: "<BUCKET2>.appspot.com"
       }
     }
  }
like image 44
Praveen Kumar Avatar answered Sep 28 '22 01:09

Praveen Kumar