Often times, you may hear that for Node.js development, the code logic should be separated into different modules.
This is logical and obviously the best practice whenever you are writing code for the real world.
In Firebase Cloud Functions, you can also do that.
index.js file, simply
require() the function from another file and use its reference to call it.
Here’s how you can do it.
For this example, I’m directly going to the index.js file.
Instead of going through a walkthrough of the
firebase init and other miscellaneous things you have to do, let’s see the
index.js file where multiple functions are defined in the same file.
This is your typical approach as a beginner where ALL your stuff is inside a single file.
In this project, we have a single
.js file where the code lives. The folder structure is as follows:
As you can see, the two functions
sayHi don’t do much.
getTimestamp function returns the server timestamp on request to the
sayHi function returns the string
Hi there depending on the query parameter in the request.
You can split them into separate files for each. Make separate files
say-hi.js in the same (or inside a
/src) folder with the code.
sayHi functions from the
The file structure looks like this after splitting our code:
But, what if, we want to do more? Like reading from Firestore, or handling users in Firebase Auth?
Let’s see what the problem is.
Initialize the project with the same
index.js file and add the Admin SDK to it.
This function reads a document from Firestore and sends it as a JSON response
curl-ing a request to the
/get-doc endpoint, you will get the data of the document with the id:
Here, we are using the Admin SDK’s functionality where it allows us to read documents from Firestore.
Let us now try to move the
getDoc function to its own separate file.
get-doc requires Admin functionality, we also need to initialize the Admin SDK in that file.
And, herein lies the problem.
In Firebase Cloud Function, you CANNOT
initializeApp() more than once.
What if you want to read a doc from Firestore which is in another file.
You might try to use the
initializeApp() method and
admin-sdk in that file too.
But, that will 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.
So, the fix to this problem is to create a separate file where you initialize the Admin SDK and
require it everywhere you want to use it.
So, the final structure of your app will look like this:
Now, you can use the
require() function to import the
db object from the Firebase Admin SDK to use it anywhere in your project.