Middy Environment Variable Middleware
raw JSON →middy-env is a middleware for the middy framework, specifically designed to parse and inject environment variables into AWS Lambda function handlers. It's currently at version 2.0.0, which aligns with the major version 2.x of the core middy framework, ensuring compatibility with the latest middy features and architecture. This package provides robust configuration management for serverless functions, allowing developers to define required environment variables, specify their expected types (string, int, float, bool), and provide fallback values to prevent runtime errors. A key differentiator is its ability to assign parsed variables directly to the Lambda `context` object by default, rather than polluting the global `process.env`, offering a cleaner and more isolated configuration scope per invocation. It also supports optional caching of parsed values to optimize performance for subsequent warm invocations, with configurable expiry times. The package maintains a stable release cadence, typically aligning with major middy framework updates.
Common errors
error ReferenceError: LAST_NAME is not defined ↓
middy-env configuration to include a fallback value for lastName (e.g., lastName: ['LAST_NAME', 'string', '']) or ensure the LAST_NAME environment variable is correctly set in your Lambda function's environment. Warnings
breaking middy-env v2.x introduces support for middy v2.x. If your project uses middy v1.x, you must use middy-env v1.x to ensure compatibility. ↓
gotcha Environment variables specified in the `names` option will cause a `ReferenceError` if they are not set in the environment and no fallback value is provided in the configuration. ↓
gotcha By default, parsed environment variables are assigned to the Lambda `context` object. They are not added to `process.env`. ↓
Install
npm install middy-env yarn add middy-env pnpm add middy-env Imports
- env wrong
const { env } = require('middy-env');correctimport env from 'middy-env'; - middy wrong
const middy = require('middy');correctimport middy from '@middy/core';
Quickstart
const middy = require('middy');
const env = require('middy-env');
const handler = async (event, context) => {
// Access variables directly from context object
const firstName = context.firstName ?? 'Guest';
const lastName = context.lastName ?? '';
return {
statusCode: 200,
body: `Hello ${firstName} ${lastName}`
};
};
module.exports = middy(handler)
.use(env({
names: {
firstName: ['FIRST_NAME', 'string', 'World'], // 'World' is fallback if FIRST_NAME env var is missing
lastName: 'LAST_NAME' // Will throw ReferenceError if LAST_NAME is missing and no fallback
},
cache: true,
cacheExpiryInMillis: 3600000 // Cache for 1 hour (3,600,000 milliseconds)
}));