DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Rajesh Kumaravel
Rajesh Kumaravel

Posted on

Google Firebase Functions : Setting and accessing environment variable

It's always a good idea to externalize application keys/secrets from code.
Google Firebase Functions has a feature that allows you to specify environment variables of key/value pairs using Firebase CLI and can be accessed by your code at runtime.

Set env variable

firebase functions:config:set config.key="SECRET_KEY" config.pass="SECRET_PASS"
Enter fullscreen mode Exit fullscreen mode

NOTE: You must redeploy functions to make the new configuration available.

Deploy functions

firebase deploy --only functions
Enter fullscreen mode Exit fullscreen mode

Accessing env variables

const secretKey  = firebase.config().config.key;
const secretPass = firebase.config().config.pass;
Enter fullscreen mode Exit fullscreen mode

Retrieve all variables

firebase functions:config:get
Enter fullscreen mode Exit fullscreen mode

Output:

{
  "config": {
    "key": "SECRET_KEY",
    "pass": "SECRET_PASS"
  }
}
Enter fullscreen mode Exit fullscreen mode

Unset a variable

firebase functions:config:unset config.key
Enter fullscreen mode Exit fullscreen mode

Let's consider using a file where we can keep all the environment variables.

env.json, a file that will contain all our environment variables.

{
  "config": {
    "host": "domain",
    "key": "SECRET_KEY",
    "pass": "SECRET_PASS"
  }
}
Enter fullscreen mode Exit fullscreen mode

How to deploy the variables with the env.json file?

firebase functions:config:set env="$(cat env.json)"
Enter fullscreen mode Exit fullscreen mode

Great! Now we can make a bulk update of our variables and keep track of them.

Top comments (3)

Collapse
 
jamm3e3333 profile image
Jakub Vala • Edited on

thank you a lot πŸ™‡ πŸ’™ I was desperate of accessing the process.env vars during the deploy, finding out it's not really working and this has saved me a lot of time. Very much appreciated

Collapse
 
mjoycemilburn profile image
MartinJ

Nice post Rajesh. But I think

const secretKey = firebase.config().config.key;
const secretPass = firebase.config().config.pass;

should reference functions.config()r rather than firebase.config()

Collapse
 
trejocode profile image
Sergio A. Trejo

Thank you <3

Hey 😍

Want to help the DEV Community feel more like a community?

Head over to the Welcome Thread and greet some new community members!

It only takes a minute of your time, and goes a long way!