1

I am using Netlify Serverless Functions. I want to retrieve and save data to the firebase firestore. I use firebase-admin SDK.

The following is the initialization:

var admin = require("firebase-admin");

var serviceAccount = require("../keys/serviceAccountKey.json");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
});

I have multiple functions and I was wondering if there's a way to initialize the firebase once. Because I have to paste the same code above in all my functions which seems very inefficient and not best practice.

I have read on global initialization in NodeJs which just exports it and then imports that code where needed. But in netlify, it's a bit different since any file I place in functions folder will be used as URL endpoint.

I am very new to Netlify so clarification is much appreciated.

Danish Saeed
  • 49
  • 1
  • 5

1 Answers1

0

You can create a separate module file for initializing the firebase app and then can use its reference across all files.

Create a file named firebase.js

var admin = require("firebase-admin");

var serviceAccount = require("../keys/serviceAccountKey.json");

var FirebaseApp = admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
});

module.exports.FirebaseApp = FirebaseApp;

In another file, use it like below

var FirebaseApp = require('/firebase.js')
var collectionRef = FirebaseApp.database().ref("collection/");
ZealousWeb
  • 1,647
  • 1
  • 10
  • 11
  • Although I was able to type "ww.URL/.netlify/functions/firebase" and it reinitialized firebase which would throw error if I was to refresh page, saying its already been initialized. But I solved that by conditional checking ```if (firebase.apps.length === 0)```. My problem has been solved. But just for general knowledge, how do I tell Netlify to not include firebase.js as a URL – Danish Saeed Jan 21 '21 at 00:53