Registry / aws / middy
library0.36.0jsnpmunverified

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.

npm install middy
INSTALL
IMPORT
SIG · MIDDY
M
middy
awsjavascriptv0.36.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

middy
import middy from '@middy/core'
const middy = require('middy')
Middy 7.x primarily uses ESM imports from scoped packages like `@middy/core`. The `require('middy')` pattern is for deprecated 0.x versions or older CommonJS setups.
jsonBodyParser
import jsonBodyParser from '@middy/http-json-body-parser'
const { jsonBodyParser } = require('middy/middlewares')
Individual middlewares are imported from their respective scoped packages in Middy 7.x. The old `middy/middlewares` path is for 0.x.
validator
import validator from '@middy/validator'
const { validator } = require('middy/middlewares')
Middy 7.x imports individual middlewares from their dedicated packages. Ensure `@middy/validator` is installed.
httpErrorHandler
import httpErrorHandler from '@middy/http-error-handler'
const { httpErrorHandler } = require('middy/middlewares')
Error handling middleware is imported from its specific package for Middy 7.x. Ensure `@middy/http-error-handler` is installed.

This quickstart demonstrates how to set up an AWS Lambda handler with Middy.js, applying `jsonBodyParser` for automatic JSON parsing, `validator` for schema validation, and `httpErrorHandler` for structured error responses. It showcases the ESM import style for Middy 7.x and basic middleware chaining.

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
Debug
Known issues
breakingMiddy 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.
fix
Migrate to Middy 7.x using the official upgrade guides. Update all `@middy/*` packages to their latest versions and adjust import paths and middleware configurations accordingly. For example, `require('middy')` changes to `import middy from '@middy/core'` and individual middlewares are imported from their own scoped packages (e.g., `@middy/http-json-body-parser`).
affects: 0.x
breakingMiddy 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.
fix
Upgrade your Lambda runtime to Node.js 24.x or newer. Replace `middy({ streamifyResponse: true })` with `middy({ executionMode: executionModeStreamifyResponse })` and ensure `executionModeStreamifyResponse` is imported from `@middy/core/StreamifyResponse`.
affects: >=7.0.0
gotchaA 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.
fix
Upgrade all `@middy/*` packages to at least 7.2.2 to incorporate the security fix. Regularly update dependencies to mitigate known vulnerabilities.
affects: >=7.2.2
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.
fix
Upgrade `@middy/http-cors` to version 7.2.2 or newer to resolve the Punycode normalization issue.
affects: >=7.1.1 <7.2.2
gotchaCompatibility 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.
fix
Check for known compatibility issues between your Middy and Lambda Power Tools versions. Refer to the Middy.js and Power Tools GitHub repositories for specific fixes or workarounds. Often, upgrading both libraries to their latest compatible versions resolves such conflicts.
affects: >=7.1.3
gotchaThe `@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.
fix
Upgrade `@middy/cloudformation-response` to 7.1.8 or newer. Version 7.1.8 includes a fix to auto-populate `PhysicalResourceId` from `context.logStreamName` when not explicitly provided.
affects: 7.1.7
Errors
Common errors & fixes
X [ERROR] Could not resolve "@aws/durable-execution-sdk-js"
Middy 7.x utilizes `@aws/durable-execution-sdk-js` for Durable Functions, which bundlers like esbuild might fail to resolve if not configured as an external dependency.
fix
Configure your bundler (e.g., esbuild) to treat `@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`.
Cannot find module '@middy/core' or its corresponding type declarations. import middy from '@middy/core';
This typically occurs when using Jest with TypeScript and ESM, as Jest's default configuration might not correctly handle ES modules (import syntax) or the specific module resolution for `@middy/core`.
fix
Update your `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`.
`@middy/http-cors`: Punycode normalization breaks origin matching for mixed-case hostnames (since v7.1.1)
A bug in `@middy/http-cors` middleware versions 7.1.1 through 7.2.1 caused issues with hostnames containing mixed-case characters due to incorrect Punycode normalization, leading to CORS failures.
fix
Upgrade your `@middy/http-cors` package to version 7.2.2 or higher to receive the fix for Punycode normalization.
`httpResponseSerializer` generates type error in Middy 7.1.4
A type definition issue in the `@middy/http-response-serializer` middleware in version 7.1.4 caused TypeScript compilation errors.
fix
Upgrade `@middy/http-response-serializer` to version 7.1.5 or newer to resolve the type error.
`API Gateway Event v2 is not accepted` in `http-event-normalizer`
The `@middy/http-event-normalizer` middleware in certain 7.x versions did not correctly process API Gateway HTTP API (v2) event structures, leading to events not being normalized as expected.
fix
Upgrade `@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.
Upgrade
Version history
0.36.0latest on npm
Audit
Dependencies
@types/aws-lambdaoptionalRequired for TypeScript users to get correct type definitions for AWS Lambda event and context objects.
@aws/durable-execution-sdk-jsrequiredUsed internally by Middy 7.x for Durable Functions; may require specific bundler configurations (e.g., marking as external) to prevent resolution errors during builds.
Agent activity
8 hits · last 30 days
node
8
Resources