Kieran Gill Kieran Gill - 1 month ago 24
Node.js Question

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!

Answer

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.

Comments