{"id":17810,"library":"middy","title":"Middy.js Middleware Engine for AWS Lambda","description":"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.","status":"active","version":"0.36.0","language":"javascript","source_language":"en","source_url":"https://github.com/middyjs/middy","tags":["javascript","Lambda","Middleware","Serverless","Framework","AWS","AWS Lambda","typescript"],"install":[{"cmd":"npm install middy","lang":"bash","label":"npm"},{"cmd":"yarn add middy","lang":"bash","label":"yarn"},{"cmd":"pnpm add middy","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for TypeScript users to get correct type definitions for AWS Lambda event and context objects.","package":"@types/aws-lambda","optional":true},{"reason":"Used internally by Middy 7.x for Durable Functions; may require specific bundler configurations (e.g., marking as external) to prevent resolution errors during builds.","package":"@aws/durable-execution-sdk-js","optional":false}],"imports":[{"note":"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.","wrong":"const middy = require('middy')","symbol":"middy","correct":"import middy from '@middy/core'"},{"note":"Individual middlewares are imported from their respective scoped packages in Middy 7.x. The old `middy/middlewares` path is for 0.x.","wrong":"const { jsonBodyParser } = require('middy/middlewares')","symbol":"jsonBodyParser","correct":"import jsonBodyParser from '@middy/http-json-body-parser'"},{"note":"Middy 7.x imports individual middlewares from their dedicated packages. Ensure `@middy/validator` is installed.","wrong":"const { validator } = require('middy/middlewares')","symbol":"validator","correct":"import validator from '@middy/validator'"},{"note":"Error handling middleware is imported from its specific package for Middy 7.x. Ensure `@middy/http-error-handler` is installed.","wrong":"const { httpErrorHandler } = require('middy/middlewares')","symbol":"httpErrorHandler","correct":"import httpErrorHandler from '@middy/http-error-handler'"}],"quickstart":{"code":"import middy from '@middy/core';\nimport jsonBodyParser from '@middy/http-json-body-parser';\nimport httpErrorHandler from '@middy/http-error-handler';\nimport validator from '@middy/validator';\n\n// Define your AWS Lambda handler function\nconst paymentHandler = async (event, context) => {\n  // Assume event.body is already parsed by jsonBodyParser\n  const { amount, currency, token } = event.body;\n\n  if (!amount || !currency || !token) {\n    throw new Error('Missing required payment details.');\n  }\n\n  // Simulate payment processing\n  console.log(`Processing payment for ${amount} ${currency} with token ${token}`);\n  const paymentId = `pay_${Date.now()}`;\n\n  return {\n    statusCode: 200,\n    headers: { 'Content-Type': 'application/json' },\n    body: JSON.stringify({ message: 'Payment processed successfully', paymentId })\n  };\n};\n\nconst inputSchema = {\n  type: 'object',\n  properties: {\n    body: {\n      type: 'object',\n      properties: {\n        amount: { type: 'number', minimum: 0.01 },\n        currency: { type: 'string', pattern: '^[A-Z]{3}$' },\n        token: { type: 'string' }\n      },\n      required: ['amount', 'currency', 'token']\n    }\n  },\n  required: ['body']\n};\n\n// Wrap your handler with middy and apply middlewares\nexport const handler = middy(paymentHandler)\n  .use(jsonBodyParser())\n  .use(validator({ inputSchema }))\n  .use(httpErrorHandler()); // Must be the last middleware for error catching","lang":"typescript","description":"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."},"warnings":[{"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`).","message":"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.","severity":"breaking","affected_versions":"0.x"},{"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`.","message":"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.","severity":"breaking","affected_versions":">=7.0.0"},{"fix":"Upgrade all `@middy/*` packages to at least 7.2.2 to incorporate the security fix. Regularly update dependencies to mitigate known vulnerabilities.","message":"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.","severity":"gotcha","affected_versions":">=7.2.2"},{"fix":"Upgrade `@middy/http-cors` to version 7.2.2 or newer to resolve the Punycode normalization issue.","message":"`@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.","severity":"gotcha","affected_versions":">=7.1.1 <7.2.2"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=7.1.3"},{"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.","message":"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.","severity":"gotcha","affected_versions":"7.1.7"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"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`.","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.","error":"X [ERROR] Could not resolve \"@aws/durable-execution-sdk-js\""},{"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`.","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`.","error":"Cannot find module '@middy/core' or its corresponding type declarations. import middy from '@middy/core';"},{"fix":"Upgrade your `@middy/http-cors` package to version 7.2.2 or higher to receive the fix for Punycode normalization.","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.","error":"`@middy/http-cors`: Punycode normalization breaks origin matching for mixed-case hostnames (since v7.1.1)"},{"fix":"Upgrade `@middy/http-response-serializer` to version 7.1.5 or newer to resolve the type error.","cause":"A type definition issue in the `@middy/http-response-serializer` middleware in version 7.1.4 caused TypeScript compilation errors.","error":"`httpResponseSerializer` generates type error in Middy 7.1.4"},{"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.","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.","error":"`API Gateway Event v2 is not accepted` in `http-event-normalizer`"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}