Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Firebase in Node.JS/express globally

In my main express file, app.js, I set up Firebase:

var firebase = require("firebase");
firebase.initializeApp({
  serviceAccount: "../Wrapper-adfd67bc8c36.json",
  databaseURL: "https://wrapper.firebaseio.com"
}); 

But when I try to access it in a routing file:

var express = require('express');
var router = express.Router();

router.get('/:id', function(req, res, next) {
    functionThatUsesFirebase(req.params.id);

    res.send(req.params.id);
});

I get the error:

firebase is not defined.

So then I tried just adding Firebase to the routing file itself:

var express = require('express');
var router = express.Router();
var firebase = require("firebase");
firebase.initializeApp({
  serviceAccount: "../Wrapper-adfd67bc8c36.json",
  databaseURL: "https://wrapper.firebaseio.com"
});

router.get('/:id', function(req, res, next) {
    functionThatUsesFirebase(req.params.id);

    res.send(req.params.id);
});

I get the console error:

Firebase App named '[DEFAULT]' already exists.

How can I make Firebase accessible to all of my routing files? Thanks!

like image 785
user82395214 Avatar asked Oct 11 '16 04:10

user82395214


1 Answers

In Node, all modules are "Singletons", also referred to as Module Caching in the Node.js docs. If you call initializeApp() once in your app.js and then require the firebase again in your router, your router's firebase will actually have the same global settings as the firebase in your app.js. This is the reason why you're getting your error Firebase App name '[DEFAULT]' already exists.

Once you call initializeApp() in your app.js, no subsequent calls will need to be made to initializeApp() anywhere else in your code. Whenever/wherever you need to interact with firebase just require('firebase') and use it.

like image 119
peteb Avatar answered Sep 28 '22 06:09

peteb