How to Use Environment Variables in Google Cloud Functions
To use environment variables in a Google Cloud Function, set them during deployment with the
--set-env-vars flag or in the Cloud Console. Inside your function code, access these variables using process.env.VARIABLE_NAME in Node.js or the equivalent in other languages.Syntax
When deploying a Cloud Function, you specify environment variables using the --set-env-vars flag followed by key-value pairs separated by commas.
Inside your function code, access these variables through your language's environment variable access method, such as process.env in Node.js.
bash
gcloud functions deploy FUNCTION_NAME \ --runtime nodejs18 \ --trigger-http \ --set-env-vars KEY1=VALUE1,KEY2=VALUE2
Example
This example shows a Node.js Cloud Function that reads an environment variable named GREETING and returns it in the HTTP response.
javascript
exports.helloEnv = (req, res) => {
const greeting = process.env.GREETING || 'Hello';
res.status(200).send(`${greeting}, world!`);
};Output
Hello, world!
Common Pitfalls
- Not setting environment variables during deployment will cause your function to see
undefinedvalues. - Trying to change environment variables inside the function code does not persist changes.
- Environment variables are case-sensitive; ensure you use the exact key names.
javascript
Wrong way:
exports.func = (req, res) => {
process.env.MY_VAR = 'new value'; // This does NOT change the env var for future calls
res.send(process.env.MY_VAR);
};
// Right way:
// Set MY_VAR during deployment with --set-env-vars MY_VAR=value
exports.func = (req, res) => {
res.send(process.env.MY_VAR);
};Quick Reference
Remember these tips when using environment variables in Cloud Functions:
- Set variables at deploy time with
--set-env-vars. - Access variables in code via
process.env.VAR_NAME(Node.js) or equivalent. - Do not attempt to modify environment variables inside the function.
- Use environment variables for secrets or config, not for large data.
Key Takeaways
Set environment variables during deployment using the --set-env-vars flag.
Access environment variables inside your function code via process.env in Node.js.
Environment variables are read-only inside the function and cannot be changed at runtime.
Use environment variables for configuration and secrets, not for large or sensitive data storage.
Ensure variable names are case-sensitive and match exactly between deployment and code.