Firebase Functions variables

Sometimes you want to use some environment or config variables in your Functions, be it to decide if you are running on your local machine or on the server, or reading API keys to use for with third party libraries.

You can access environment variables by looking at process.env.

If you want to know if your function in running on the server you can check the NODE_ENV variable. A simple use case would be initializing the firebase-admin SDK to get access to you database. You can load the needed credentials from functions.config().firebase if running in production, but need to load credentials from a file when testing.

Do get an idea of what is available as environment variables when running a function, here is a dump of mine (with my personal details replaced by <placeholders>).

{
"WORKER_PORT":"8091",
"GCLOUD_PROJECT":"<project_name>",
"FUNCTION_NAME":"<function_name>",
"SUPERVISOR_HOSTNAME":"192.168.1.1",
"PATH":"/usr/local/bin:/usr/bin:/bin",
"PWD":"/user_code",
"FUNCTION_TRIGGER_TYPE":"HTTP_TRIGGER",
"FUNCTION_TIMEOUT_SEC":"60",
"NODE_ENV":"production",
"SHLVL":"1",
"CODE_LOCATION":"/user_code",
"GCP_PROJECT":"<project_name>",
"FUNCTION_MEMORY_MB":"256",
"PORT":"8080",
"SUPERVISOR_INTERNAL_PORT":"8081",
"ENTRY_POINT":"<function_name>",
"OLDPWD":"/var/tmp/worker/",
"_":"/usr/bin/env",
"HOME":"/tmp"
}

If you have any API keys you want to use, you can add it to your functions config by running

firebase functions:config:set someservice.key="THE API KEY" someservice.id="THE CLIENT ID"

or for a practical example

firebase functions:config:set third_party.key=”My Test Key”

and then access it with

functions.config().third_party.key

By default functions.config() only contains the firebase object but you can add as many extra objects as you want. Mine now looks like this:

{  
"third_party":{
"key":"My Test Key"
},
"firebase":{
"databaseURL":"https://<project_name>.firebaseio.com",
"storageBucket":"<project_name>.appspot.com",
"apiKey":"<api_key>",
"authDomain":"<project_name>.firebaseapp.com",
"projectId":"<project_name>",
"credential":{
"credential_":{}
}
}
}