Access Firebase in Node.JS / express globally

In my main express app.js file app.js I installed Firebase:

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

But when I try to access it in the 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 an error message:

 firebase is not defined. 

So, 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 a console error:

 Firebase App named '[DEFAULT]' already exists. 

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

+5
source share
1 answer

In Node, all modules are "Singletons" , also called Caching Modules in Node.js. If you call initializeApp() once in your app.js and then again require firebase in your router, your firebase router firebase actually have the same global settings as firebase in your app.js It is for this reason that you get your error. Firebase App name '[DEFAULT]' already exists .

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

+6
source

Source: https://habr.com/ru/post/1258004/


All Articles