Skip to content

Environment Variables

Environment Variables sits at the heart of lambda configuration in AWS Lambda. This guide walks through the concept step by step, with examples, a cheatsheet, and common mistakes to avoid.

Environment Variables Overview

Environment Variables is a building block you will reach for often in AWS Lambda. It keeps related logic together and makes your intent obvious to reviewers and future maintainers.

When you learn environment variables properly, you avoid the guesswork that leads to bugs and rework. The example below shows the shape you will use in most real AWS Lambda projects.

import { SSMClient, GetParameterCommand } from '@aws-sdk/client-ssm';

const ssm = new SSMClient({});
let cachedApiKey;

export const handler = async () => {
  if (!cachedApiKey) {
    const { Parameter } = await ssm.send(new GetParameterCommand({
      Name: '/app/api-key',
      WithDecryption: true,
    }));
    cachedApiKey = Parameter.Value;
  }

  return { hasKey: Boolean(cachedApiKey) };
};

Configuration is fetched once and cached in module scope so warm invocations skip the extra call.

Environment Variables Example

// handler.mjs
export const handler = async (event, context) => {
  // 1. read input from the event
  // 2. do the work
  // 3. return a response (or throw on error)
};
  • Start from a minimal Environment Variables example and grow it only as needed.
  • Keep configuration explicit so Environment Variables behaves the same in every environment.
  • Name things clearly so teammates understand your Environment Variables at a glance.
  • Add tests around Environment Variables early to lock in expected behaviour.

AWS Lambda Cheatsheet

Handy reference for working with environment variables in AWS Lambda and Node.js.

Task Example Purpose
Define handler export const handler = async (event) => {} Entry point AWS invokes
Read input event.body, event.Records Access request or trigger data
Return response { statusCode, body } Reply through API Gateway
Reuse SDK client const c = new S3Client({}) (module scope) Faster warm invocations
Env config process.env.TABLE_NAME Externalise settings
Log console.log(JSON.stringify(obj)) Structured CloudWatch logs
Deploy sam deploy / serverless deploy Ship the function

How Environment Variables Works in AWS Lambda

Environment Variables runs inside the managed Lambda execution environment. AWS provisions a micro-VM, loads your Node.js code, runs any module-scope initialisation once, and then invokes your handler for each event.

Configuration is fetched once and cached in module scope so warm invocations skip the extra call.

  • Handlers should be small and do one job well.
  • Initialise SDK clients and config outside the handler to reuse them on warm starts.
  • Return quickly and let event sources handle retries where possible.
  • Emit structured logs so CloudWatch and X-Ray can correlate activity.

Practical Guidance for Environment Variables

On real projects, environment variables works best when it is observable, secure, and cheap to run. Grant least-privilege IAM, validate every input, and keep the deployment package small.

Concern Recommendation
Security Least-privilege IAM role, validate all input
Performance Reuse clients, right-size memory, avoid heavy cold starts
Reliability Idempotent handlers, dead-letter queues for failures
Observability Structured logs, metrics, and X-Ray tracing

Common Mistakes

  • Skipping error handling and edge cases when wiring up environment variables.
  • Leaving environment variables untested, so regressions slip into production.
  • Over-engineering environment variables before you actually need the extra flexibility.
  • Ignoring documentation, which makes environment variables hard for the next developer to change.

Key Takeaways

  • Environment Variables is a core part of working effectively with AWS Lambda.
  • Start small and keep environment variables focused on a single responsibility.
  • Apply consistent patterns so environment variables scales across your project.
  • Test and document environment variables to keep it maintainable over time.

Pro Tip

Pair environment variables with automated tests from day one. It is far cheaper to catch AWS Lambda regressions in CI than in production.