Search code examples
javascriptnode.jsfirebasegoogle-cloud-functionsdotenv

Firebase Cloud Functions - ENV Variables Outside Of Function


I am trying to use a process.env value outside of a cloud function definition however its just getting undefined when I am not using the variable inside a cloud function.

functions/.env

OPENAI_API_KEY=MY_API_KEY

functions/index.js

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const { ChatOpenAI } = require("@langchain/openai");

console.log(process.env.OPENAI_API_KEY); // undefined

const llm = new ChatOpenAI({
  openAIApiKey: process.env.OPENAI_API_KEY, // undefined
});


exports.testCall = functions.https.onCall((data, context) => {
  console.log(process.env.OPENAI_API_KEY); // defined with proper value  
});

I'm new to firebase and cloud functions so maybe there is some sort paradigm that I am not understanding but I'm confused on how I can use env variables outside of a function.

When I start my firebase emulator it says "Loaded environment variables from .env." however again its only available at function runtime.


Solution

  • What you're describing is the expected behavior and can't be changed.

    In your particular case, that means you should not use env vars at the global scope of your code. Instead, you can lazy-initialize any global scope variable upon the first invocation of the function.

    let llm;
    
    exports.testCall = functions.https.onCall((data, context) => {
      if (llm === undefined) {
        llm = new ChatOpenAI({
          openAIApiKey: process.env.OPENAI_API_KEY,
        });
      }
    
      // use llm normally
    });