skip to Main Content

I’m upgrading firebase functions, I’m setting up secret manager env vars, however they are only available INSIDE the export function, this means that third party module will need to be initialized every time they are called, is this right?

Normally I would do something like this

var myModule = require("myModule");

myModule.initiliaze({
  KEY:process.env.SECRET_KEY
})

exports.myFunction = onCall((request) => {
  return myModule.process();
});

But now with secrets not being available outside exports it would have to look like this

var myModule = require("myModule");

exports.myFunction = onCall((request) => {
  myModule.initiliaze({
    KEY:process.env.SECRET_KEY
  })
  
  return myModule.process();
});

If I get a hundred calls an hour, do I really want to initialize 100 separate times?

2

Answers


  1. Chosen as BEST ANSWER

    For some reason my secret vars are unavailable when I first start the emulator, but then become available upon the first call, I still don't want to have initialization code in every single functions, so I ended up with this at the top of the file outside all the exported functions

    initializeApp();
    
    var userApp;
    var userAppDB;
    var allInitilized = false;
    
    if (process.env.KEY_FILE_PATH && !allInitilized) {
        userApp = initializeApp({
            credential: cert(process.env.KEY_FILE_PATH),
            databaseURL: process.env.DATABASE_URL
        }, "userApp");
    
        userAppDB = getFirestore(userApp);
    
        ...
    
        allInitilized = true
    };
    

  2. I’m not sure why your secrets aren’t available in the first code snippet, but if you want to prevent initializing the SDK on each call – consider using a variable to track whether it’s already been initialized in this Functions container.

    Something like:

    var myModule = require("myModule");
    var isMyModuleInitialized = false;
    
    exports.myFunction = onCall((request) => {
      if (!isMyModuleInitialized) {
        myModule.initiliaze({
          KEY:process.env.SECRET_KEY
        })
        isMyModuleInitialized = true;
      }
      
      return myModule.process();
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search