Environment variables
Firebase provides a way to register and manage secrets through the CLI. We then read them from Cloud functions, both from deployed functions and from functions running locally in the emulator.
As such, we don't need to store secrets in local .env files.
Manage secrets
set, read and destroy secrets through the CLI
firebase functions:secrets:set ABC_API_KEY
firebase functions:secrets:access ABC_API_KEY
firebase functions:secrets:destroy ABC_API_KEY
gcloud secrets list --project <PROJECT_ID>
Note: the secrets are available both locally (function emulator) and for deployed functions.
read secrets from cloud functions
We declare the secrets requirements in the function options. We then read them from process.env:
const options: CallableOptions = {
// ..
secrets: ["ABC_API_KEY"],
}
onCall<ReqData, Promise<ResData>>(options, async (request) => {
const abcKey = process.env.ABC_API_KEY
})
Https functions:
const options: HttpsOptions = {
// ..
secrets: ["ABC_API_KEY"],
}
onRequest(options, (req, res) => {
const abcKey = process.env.ABC_API_KEY
})
.env file pattern
The .env file pattern should be only used if the CLI pattern is not available or not applicable. We set the env variables in a .env file:
ABC_API_KEY=xxx
The key is then made available to cloud functions the same way as seen above, at process.env, both locally and for deployed functions, as long as the key is listed in the options.
On deploy, the .env file is automatically detected and deployed along functions. See env-variables docs