Long Sang Chan Long Sang Chan - 4 months ago 848
Javascript Question

Initialize Firebase references in two separate files in the new API

I have upgraded to the new API and don't know how to initialize Firebase references in two separate files:

/* CASE 1 */
// 1st file
var config = {/* ... */};
firebase.initializeApp(config);
var rootRef = firebase.database().ref();

// 2nd file - initialize again
var config = {/* ... */};
firebase.initializeApp(config);
var rootRef = firebase.database().ref();



RESULT: bundle.js:535 Uncaught Error: Firebase App named '[DEFAULT]' already exists.


/* CASE 2 */
// 1st file
var config = {/* ... */};
firebase.initializeApp(config);
var rootRef = firebase.database().ref();

// 2nd file - don't initialize
var rootRef = firebase.database().ref();



RESULT: bundle.js:529 Uncaught Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp().


Before the new API I just called

var myFirebaseRef = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");


in each file, and it worked okay.

Answer

This is an issue I ran into as well upgrading to the new version of Firebase. You might want two separate firebase apps initialized, like explained in other answers, but I just wanted to use the refs in two different locations in my app and I was getting the same error.

What you need to do for this situation is to create a firebase module for your app that only initializes firebase once, then you import or require it elsewhere in your app.

This is pretty simple, here is mine: modules/firebase.js

import firebase from 'firebase';
var firebaseConfig = {
  apiKey: "some-api-key",
  authDomain: "some-app.firebaseapp.com",
  databaseURL: "https://some-app.firebaseio.com",
  storageBucket: "some-app.appspot.com",
};

var FbApp = firebase.initializeApp(firebaseConfig);
module.exports.FBApp = FbApp.database(); //this doesnt have to be database only

And then elsewhere in your application you simply:

import FBApp from '/your/module/location'
var messagesRef = FBApp.ref("messages/");