Middy.js Middleware Engine for AWS Lambda
raw JSON →Middy is a Node.js middleware engine specifically designed for AWS Lambda functions, bringing an Express.js-like middleware pattern to serverless environments. It allows developers to encapsulate common logic such as input parsing, validation, authentication, and error handling into reusable middleware functions, enhancing code modularity and maintainability for Lambda handlers. The current stable version series is 7.x, with recent releases like 7.3.1 focusing on improvements, security fixes, and compatibility. Previously, there was a significant breaking change from the 0.x series to 1.x, and subsequently to the 7.x series, requiring migration for older projects. Middy provides a rich ecosystem of official and third-party middlewares for common Lambda patterns, differentiating itself by its focus on simplicity, performance, and a clear execution lifecycle for `before`, `after`, and `onError` hooks.
Common errors
error X [ERROR] Could not resolve "@aws/durable-execution-sdk-js" ↓
@aws/durable-execution-sdk-js as an external package. For esbuild, add --external:@aws/durable-execution-sdk-js to your build command or configure it in your esbuild.config.js. error Cannot find module '@middy/core' or its corresponding type declarations. import middy from '@middy/core'; ↓
jest.config.js to properly transform @middy/core for ESM. This often involves transformIgnorePatterns (e.g., /node_modules/(?!(@middy/core)/)), moduleNameMapper ('^@middy/core$': '<rootDir>/node_modules/@middy/core'), and configuring ts-jest to useESM: true, along with a babel.config.js. error `@middy/http-cors`: Punycode normalization breaks origin matching for mixed-case hostnames (since v7.1.1) ↓
@middy/http-cors package to version 7.2.2 or higher to receive the fix for Punycode normalization. error `httpResponseSerializer` generates type error in Middy 7.1.4 ↓
@middy/http-response-serializer to version 7.1.5 or newer to resolve the type error. error `API Gateway Event v2 is not accepted` in `http-event-normalizer` ↓
@middy/http-event-normalizer to the latest 7.x patch version (e.g., 7.1.5 or newer) that includes support and fixes for API Gateway Event v2. Warnings
breaking Middy 0.x is deprecated and no longer supported. Significant breaking changes occurred when migrating to 1.x (Jan 2020) and subsequently to the current 7.x series. Projects on 0.x require substantial refactoring and dependency updates. ↓
breaking Middy 7.x no longer supports Node.js versions 20.x, with a strong recommendation to upgrade to Node.js 24.x for optimal compatibility and performance. Additionally, the `streamifyResponse` option has been deprecated and replaced by an `executionMode` property for stream-based responses. ↓
gotcha A low-risk Prototype Pollution vulnerability was identified in `@middy/util` affecting `internal` properties. While patches have been released, ensure you are on the latest patch versions of Middy 7.x. ↓
gotcha `@middy/http-cors` versions 7.1.1 onwards had an issue with Punycode normalization, causing origin matching to fail for mixed-case hostnames, potentially leading to incorrect CORS behavior. ↓
gotcha Compatibility with AWS Lambda Power Tools for TypeScript can be broken in certain Middy 7.x versions, particularly 7.1.3 and above, due to internal changes or conflicting dependency resolutions. ↓
gotcha The `@middy/cloudformation-response` middleware version 7.1.7 caused issues with CloudFormation custom resource lifecycle, potentially leading to deployment failures if the `PhysicalResourceId` was not explicitly set. ↓
Install
npm install middy yarn add middy pnpm add middy Imports
- middy wrong
const middy = require('middy')correctimport middy from '@middy/core' - jsonBodyParser wrong
const { jsonBodyParser } = require('middy/middlewares')correctimport jsonBodyParser from '@middy/http-json-body-parser' - validator wrong
const { validator } = require('middy/middlewares')correctimport validator from '@middy/validator' - httpErrorHandler wrong
const { httpErrorHandler } = require('middy/middlewares')correctimport httpErrorHandler from '@middy/http-error-handler'
Quickstart
import middy from '@middy/core';
import jsonBodyParser from '@middy/http-json-body-parser';
import httpErrorHandler from '@middy/http-error-handler';
import validator from '@middy/validator';
// Define your AWS Lambda handler function
const paymentHandler = async (event, context) => {
// Assume event.body is already parsed by jsonBodyParser
const { amount, currency, token } = event.body;
if (!amount || !currency || !token) {
throw new Error('Missing required payment details.');
}
// Simulate payment processing
console.log(`Processing payment for ${amount} ${currency} with token ${token}`);
const paymentId = `pay_${Date.now()}`;
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: 'Payment processed successfully', paymentId })
};
};
const inputSchema = {
type: 'object',
properties: {
body: {
type: 'object',
properties: {
amount: { type: 'number', minimum: 0.01 },
currency: { type: 'string', pattern: '^[A-Z]{3}$' },
token: { type: 'string' }
},
required: ['amount', 'currency', 'token']
}
},
required: ['body']
};
// Wrap your handler with middy and apply middlewares
export const handler = middy(paymentHandler)
.use(jsonBodyParser())
.use(validator({ inputSchema }))
.use(httpErrorHandler()); // Must be the last middleware for error catching