How do you setup local environment variables for Cloud Functions for Firebase
As of now, you have to manually create a .runtimeconfig.json
file inside your functions directory by running this command. Then run the serve command.
firebase functions:config:get > .runtimeconfig.json
If you are using Windows Powershell, replace the above with:
firebase functions:config:get | ac .runtimeconfig.json
You can learn more in https://firebase.google.com/docs/functions/local-emulator
For those who want to use the environment variables (process.env), I follow this workaround.
Set the config values before deploying
firebase functions:config:set envs.db_host=$DB_HOST_PROD envs.db_user=$DB_USER_PROD envs.db_password=$DB_PASSWORD_PROD envs.db_name=$DB_NAME_PROD envs.db_use_ssl=false
Read the config and update the env variables first thing under your functions code.
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];
}
You can keep a file called .env.json and load it when you trigger deploy command
{
"name": "project",
"version": "0.0.0",
"scripts": {
"deploy": "npm run env && firebase deploy --only functions",
"env": "test -f env.json && firebase functions:config:unset env && firebase functions:config:set env=\"$(cat env.json)\" || echo \"Please add the file env.json before deploy.\""
},
"dependencies": {
"firebase-functions": "^3.1.0"
},
"devDependencies": {
"firebase-functions-test": "^0.1.6"
}
}
I've narrowed down the issue to Windows Powershell.
Running firebase functions:config:get > .runtimeconfig.json
in powershell generates a broken json I don't know why, which when parsed gives Unexpected token � in JSON at position 0.
I've managed to sort it out by running .runtimeconfig.json generation command in Windows command prompt.