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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With