6

I tried to split all my function in many files but I've a problem with firebase-admin initialization. I've my first file like this:

const functions = require('firebase-functions'); const admin = require('firebase-admin') admin.initializeApp(functions.config().firebase) const userHandler = require('./user') 

and second file user.js

const functions = require('firebase-functions') const admin = require('firebase-admin') ... exports.update = (req, res) => { admin.auth().verifyIdToken(req.body).catch(error => {console.log(error)} } 

All in a single file it works perfectly, in 2 separate file give me this error:

ReferenceError: ISTANCE_NAME is not defined 

I can't do a second initializeApp in a user.js because firebase throw an error:

Error: The default Firebase app already exists. This means you called initializeApp() more than once without providing an app name as the second argument. In most cases you only need to call initializeApp() once. But if you do want to initialize multiple apps, pass a second argument to initializeApp() to give each app a unique name.

How I can use the same istance of admin shared in 2 files? I've tried also to put the initializeApp function in another file and import it but not works, same error (ISTANCE_NAME is not defined)

1
  • did you figure this out eventually? If so, please share the answer. Commented Aug 26, 2019 at 12:51

1 Answer 1

1

that's a good question.

So you're correct in saying that you can only call admin.initializeApp() once.

index.js

const functions = require('firebase-functions'); const admin = require('firebase-admin') admin.initializeApp(functions.config().firebase) const userHandler = require('./user') 

user.js

const admin = require('firebase-admin') 

You do not need to initialize it again. The configuration is stored correctly after it's first initialized.

Alternatively, you can do messier things like a getAdmin() function.

The way I've done it in the past is have the functions defined and make separate files with handler functions, which look like

updateHandler(req, res, admin); // or the other updateHander(whateverParamsToOtherFile); 

Note

All your functions must be exported from the index.js file to be correctly deployed on Firebase. I'd recommend the index.js to store all the functions and it calls handlers from other files.

Through parameter passing, you can achieve the result you're after. But in the specific case of admin.initializeApp(), it'll work fine in other files if it's initialized in the index.js.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.