Save and Access Environment Variables in Firebase

Environment variables in the cloud functions allows you to set/get key values at the time of deployment which can later be used in the code through environment variables. Firebase cloud functions also allows to specify key value pairs as config environment variables.

Environment variables can be saved by setting config set command through firebase CLI. Once  Firebase project is setup you can call Firebase CLI config set function to store key value pairs.

How to deploy environment variables

Suppose you want to save database configuration in environemnt variables then it can be set by calling functions:config:set command.

firebase functions:config:set db.DB_USER="username" db.DB_PASSWORD="password" db.DB_HOST="host_url" db.DB_NAME="database_name"

Please note after saving config key value pairs you need to deploy functions to the cloud. for new configuration variables to be available in the cloud.

firebase deploy functions

How to access environment variables in cloud function

Now after we have deployed config variables its time to see how we can use them in Firebase cloud code.

Config variables can be accessed via firebase.config() . Example of setting our database connection to external MySql database is shown in the below snippet.

 

Leave a Reply