Middy.js Middleware Engine for AWS Lambda

raw JSON →
0.36.0 verified Thu Apr 23 auth: no javascript

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.

error X [ERROR] Could not resolve "@aws/durable-execution-sdk-js"
cause 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.
error Cannot find module '@middy/core' or its corresponding type declarations. import middy from '@middy/core';
cause 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.
error `@middy/http-cors`: Punycode normalization breaks origin matching for mixed-case hostnames (since v7.1.1)
cause 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.
error `httpResponseSerializer` generates type error in Middy 7.1.4
cause 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.
error `API Gateway Event v2 is not accepted` in `http-event-normalizer`
cause 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.
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.
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`).
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.
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`.
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.
fix Upgrade all `@middy/*` packages to at least 7.2.2 to incorporate the security fix. Regularly update dependencies to mitigate known vulnerabilities.
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.
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.
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.
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.
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.
npm install middy
yarn add middy
pnpm add middy

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