简体   繁体   中英

Firebase Functions environment variables

So i was migrating my app from node express to firebase-functions!

In my node-express app I have.env file which contains all the data, FOr starters let's consider this as my.env file

GOOGLE_CLIENT_ID = 4046108-bssbfjohpj94l0dhpu69vpgs1ne0.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET = lTQHpj3yY57oQpO

And then in my passport strategy, I have something like this

passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL:  "/auth/google/callback",
    userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo',
    accessType: 'offline',
    passReqToCallback: true
  },

Now,

Question: 1 - Firebase-functions probably don't support.env file, so can we set env variable without manually adding it using set flag? let's say I have lot variable in my environment

Question - 2: Can I access the variable I set by doing something like this

firebase functions:config:set slack.url=https://hooks.slack.com/services/XXX

using

 process.env.slack.url

or we have to do (necessary)

functions.config().slack.url

Question:3 From Firebase Docs , it is written

There are environment variables that are automatically populated in the functions runtime and in locally emulated functions, including:

process.env.GCLOUD_PROJECT: Provides the Firebase project ID

process.env.FIREBASE_CONFIG: Provides the following Firebase project config info:

What do they mean when they mean? and if the answer to the question two is false then how are they using process.env.FIREBASE_CONFIG:

Reminder

Unlike dotenv Firebase environment files should start with .env .

So, file.env will have to be named be .env.file for it to work in firebase functions.

Answer for question 1:

Please note that, at this time, there doesn't appear to be a supported way to deploy true environment variables along with your function(s) using the firebase CLI tool. You can instead provide it as function.config() information, which is their recommended alternative to environment variables.

If you really really want to avoid function config, "pure" google cloud functions support setting environment variables. This page is a walkthrough of how to use a .env.yaml file and ultimately access those values from process.env in your code base. I know your file wasn't *.yaml, but this is a good solution (with some minor refactoring to YAML format).

The short version:

gcloud functions deploy FUNCTION_NAME --env-vars-file .env.yaml FLAGS

Answer for question 2

There is a difference between Firebase function config key/value pairs (ie function.config() ) and process.env access. They are similar in purpose, but persist data in different places (ie in Firebase's services vs actual environment variables). Thus, the syntax for accessing each one is different.

Answer for question 3

Firebase has some process.env variables available to you by convention. They're simply documenting that for your convenience, so you can assume those are there and available as true environment variables (and not function.config() values).

Again, as of right now, the CLI tool doesn't seem to let you set true environment variables. So you'll have to go with function config, or do some other hack similar to this , which takes your function config key/values and sets them as environment variables at runtime.

const functions = require('firebase-functions');
const config = functions.config();
// Porting envs from firebase config
for (const key in config.envs){
  process.env[key.toUpperCase()] = config.envs[key];
}

There's a better way as of Feb 16, 2022 : Firebase now supports .env , .env.prod , .env.dev files natively!

Documentation: https://firebase.google.com/docs/functions/config-env

You can create your env files and then use firebase use dev or firebase use prod before you deploy.

These variables can be accessed via process.env.VARIABLE_NAME

I just had a need for this and came to a different solution than what was provided here.

First, there are a lot of discussions about why you should separate secrets from configuration. Firebase allows us to do that with the .env , .env.local , .env.dev , etc files. It is a best practice to store configuration here, not secrets.

Straight from their docs

Environment variables stored in.env files can be used for function configuration, but you should not consider them a secure way to store sensitive information such as database credentials or API keys. This is especially important if you check your.env files into source control.

What hasn't been discussed is how to store secrets. The values from the OP appear to be secrets and not configuration so in my opinion this is a relevant addition to this question.

Firebase functions have access to Cloud Secret Manager .

To help you store sensitive configuration information, Cloud Functions for Firebase integrates with Google Cloud Secret Manager. This encrypted service stores configuration values securely, while still allowing easy access from your functions when needed.

You can import runWith and defineSecret to define and access your secret.

import { runWith } from 'firebase-functions/v1';
import { defineSecret } from 'firebase-functions/params';

const secretApiKey = defineSecret('MY_API_KEY');

const functionName = runWith({ secrets: [secretApiKey] })

  // ...
  client.setApiKey(process.env.MY_API_KEY);
  // ...

export default functionName;

This works with https functions, as well as auth, storage, and firebase triggers.

const onFirestore = runWith({ secrets: [secretApiKey] })
  .firestore.document('/the/{docId}')
  .onCreate(async (snap) => {

const onStorage = runWith({ secrets: [secretApiKey] })
  .storage().bucket().object()
  .onCreate(async (object) => {

Some note worthy caveats

The service account deploying the function needs the secret manager admin role.

Whenever you set a new value for a secret, you must redeploy all functions that reference that secret for them to pick up the latest value.

If you delete a secret, make sure that none of your deployed functions references that secret. Functions that use a secret value that has been deleted will fail silently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM