Search code examples
javascriptnode.jsnetlify-functionnetlify-cli

Netlify & Firebase


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.


Solution

  • 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/");