Using Environment Variables in Lambda: A Configuration Guide
Learn how to use Lambda environment variables to decouple configuration from your code, enabling dynamic updates without redeploying your functions.
Previously in this course, we discussed managing Lambda execution environments by adjusting memory, timeouts, and IAM roles. In this lesson, we shift our focus to Configuration Management. Specifically, we will decouple your code from its operational settings using environment variables, allowing you to change behavior without touching your source code.
Why Use Environment Variables in Lambda?
Hardcoding values like database table names, API endpoints, or feature flags is a common beginner mistake. If you hardcode a staging database URL, you'll have to rewrite and redeploy your code just to point it to a production database.
Environment variables provide a bridge between your application logic and the infrastructure hosting it. By using them, you keep your code generic and reusable across different environments (dev, test, prod) while keeping configuration externalized.
Defining Environment Variables in AWS
You can define environment variables directly in the Lambda console. These are key-value pairs stored in the function's configuration, which the Lambda runtime makes available to your code as a standard environment object.
- Navigate to your Lambda function in the AWS Management Console.
- Select the Configuration tab.
- Click Environment variables in the left sidebar.
- Click Edit and then Add environment variable.
- Enter a key (e.g.,
TABLE_NAME) and a value (e.g.,UsersTable-Prod). - Click Save.
AWS encrypts these variables at rest by default. If you need to store sensitive information like API keys, you can use AWS KMS to encrypt them further, though for highly sensitive secrets, AWS Secrets Manager is the industry-standard recommendation.
Accessing Variables in Node.js
Inside your Node.js Lambda function, you don't need any special libraries to read these values. The Node.js runtime automatically populates the global process.env object with your defined variables.
Here is a concrete example of how to access these variables in your index.js:
JAVASCRIPTexports.handler = async (event) => { // Access the variable defined in the Lambda Configuration const tableName = process.env.TABLE_NAME; // Provide a fallback value if the variable is missing const logLevel = process.env.LOG_LEVEL || CE9178">'INFO'; console.log(CE9178">`Working with table: ${tableName}`); console.log(CE9178">`Current log level: ${logLevel}`); return { statusCode: 200, body: JSON.stringify({ message: "Configuration loaded successfully" }), }; };
Because process.env is just a standard JavaScript object, you can access keys using dot notation (process.env.MY_VAR) or bracket notation (process.env['MY_VAR']).
Updating Variables Without Redeploying
One of the primary benefits of this approach is operational agility. If you need to point your function to a new database table or toggle a feature flag, you simply update the value in the Lambda console and hit Save.
The next time your function executes, the new environment variable value will be available. You do not need to upload a new .zip file or run a new build pipeline. This is a massive time-saver for emergency configuration changes.
Hands-on Exercise
- Open the Lambda function you created in previous lessons.
- Add an environment variable named
APP_ENVIRONMENTwith the valuedevelopment. - Update your
index.jscode to log the value ofprocess.env.APP_ENVIRONMENT. - Deploy your code, then run a test execution.
- Check your CloudWatch logs to verify the output.
- Change the
APP_ENVIRONMENTvalue in the console toproductionand trigger the function again without changing any code. Verify the log update.
Common Pitfalls
- Missing Variables: If you try to access a variable that hasn't been defined,
process.env.KEYwill returnundefined. Always implement defensive coding or provide default values (e.g.,const val = process.env.VAL || 'default'). - Case Sensitivity: Environment variable keys are case-sensitive.
TABLE_NAMEis not the same astable_name. - Over-reliance: Do not store large JSON blobs in environment variables. Lambda has a limit on the total size of environment variables (currently 4 KB). If your configuration is massive, store it in an S3 bucket or use a dedicated configuration service.
- Security: Never log
process.envdirectly in your code. It might contain sensitive credentials or internal path information that shouldn't end up in plain text logs.
FAQ
Q: Are environment variables safe for passwords? A: They are encrypted at rest, but they are visible to anyone with "View" permissions on the Lambda configuration. For production-grade security, use AWS Secrets Manager.
Q: Can I change environment variables via the AWS CLI?
A: Yes. You can use the aws lambda update-function-configuration command to update variables programmatically, which is excellent for CI/CD pipelines.
Q: Is there a way to validate these variables before the code runs? A: Yes, many developers use schema validation libraries to ensure required variables exist. For a deeper dive into this, see TypeScript Environment Variables: Preventing Runtime Config Errors.
Recap
We have successfully decoupled our configuration from our logic. By using process.env in Node.js and defining variables in the AWS Lambda configuration, we've enabled dynamic environment management. This pattern is essential for maintaining clean, portable code that behaves differently based on its deployment context.
Up next: Triggering Lambda Functions, where we'll look at how external events (like S3 uploads or API calls) actually kick off our code execution.

