Middy middleware is my simplest answer to a question that shows up in almost every Lambda project sooner or later: why does every handler start with the same code? Parse the body, check headers, validate input, turn errors into a clean HTTP response, pass a correlation ID along. That quickly adds up to 30 lines of boilerplate before the actual business logic even begins. And because everyone copies those lines a little differently, every function ends up behaving a little differently.
In this article, we build a small API for a library together: members borrow books. The handler contains nothing but the lending logic. Everything around it is handled by middlewares – two ready-made ones from the Middy ecosystem and two we write ourselves. On top of that, you get tests with Vitest, a deployment with the Serverless Framework and the typical pitfalls around ordering that almost everyone runs into.
In short
Middy wraps reusable middlewares around your Lambda handler like onion layers, so parsing, validation and error handling are not rebuilt in every function. The key insight: the order in
.use()decides when before, after and onError run. The biggest pitfall is an early response from a before phase, because it skips the handler and every after phase.
What you will learn in this article
- How Middy wraps before, after and onError around your handler
- How to write your own typed middlewares in TypeScript
- Why the order in .use() decides what your error responses look like
- How to test Middy handlers with Vitest without an AWS account
- How to deploy everything with the Serverless Framework on Node.js 24
What is Middy middleware and what problem does it solve?
A middleware is a piece of code that runs before or after your actual function and takes care of a single cross-cutting concern. Cross-cutting concerns are things every function needs that have nothing to do with its business purpose: logging, authentication, validation, error formats. If you have worked with Express or Koa, you already know the idea.
Lambda itself does not offer anything like that. A handler receives an event and a context and returns a result, nothing more. Middy fills that gap. The library is open source (MIT license), built exclusively for AWS Lambda, and consists of a small core, @middy/core, plus many separate packages for common tasks. You only install what you need. The current version is 7.9.2. Since version 7, Middy requires at least Node.js 22, the maintainers recommend Node.js 24, and Lambda offers that as the nodejs24.x runtime.
The real gain lies less in saved lines than in consistency. When all functions use the same error middleware, they all return the same error format. In addition, the handler becomes as testable as any plain function, because it only contains business logic.
How does Middy work? The onion model
Middy wraps your handler in layers. Each middleware is an object with up to three functions: before, after and onError. All three receive the same request object with event, context, response, error and a free area called internal for data that middlewares want to share with each other.
🎬 Middy onion model: request goes in, response comes out – this animated diagram only runs on my site: watch it on sascha-ms.de
before, handler, after
On a successful invocation, all before functions run first, in the order you registered them with .use(). Then the handler runs. After that come the after functions, in reverse: the most recently registered middleware goes first. That is exactly what makes the onion picture work. Whoever goes in first comes out last.
onError and early responses
If any part of the chain throws an error, Middy switches to the onError phase. It also runs in reverse, and it runs for all registered middlewares, no matter where the error came from. An onError function can turn the error into a response by setting request.response. If the response stays empty, Middy rethrows the error at the end and Lambda reports a failure.
A before function can also cut the chain short by returning a value. This is handy for caches or a maintenance mode. The returned value immediately becomes the response. Important: this skips not only the handler but also every after function. I will come back to this in the section on common mistakes.
Setting up Middy middleware in TypeScript step by step
Our example is a library. POST /loans accepts a loan request: book ID, member ID and the loan period in days. Reference books (book IDs starting with ref-) cannot be borrowed. To keep the focus on Middy, the handler does not store anything and only calculates the due date. How to persist the loan in DynamoDB is a topic of its own.
Prerequisites
- Node.js 22 or newer (Node.js 24 recommended for Lambda)
- Basic knowledge of TypeScript and AWS Lambda
- For the deployment: an AWS account and Serverless Framework v4 (
npm i -g serverless); v4 asks you to log in on first use
Step 1: Create the project
Middy is published as ES modules only. That is why the package.json contains "type": "module", and the tsconfig.json uses NodeNext for module resolution.
mkdir library-loans && cd library-loans npm init -y npm pkg set type=module npm i @middy/core @middy/http-error-handler @middy/http-header-normalizer @middy/http-json-body-parser http-errors npm i -D typescript @types/aws-lambda @types/http-errors @types/node vitest mkdir -p src/middlewares src/handlers test { "compilerOptions": { "target": "ES2023", "module": "NodeNext", "moduleResolution": "NodeNext", "strict": true, "noEmit": true, "esModuleInterop": true, "skipLibCheck": true, "types": ["node"] }, "include": ["src", "test"] } Step 2: Your own middleware for the correlation ID
A correlation ID is a unique identifier that follows a request through every system involved. If the caller sends one in the x-correlation-id header, we reuse it, otherwise we generate a new one. We return it in the response so that support requests and logs can be matched up.
This first custom Middy middleware follows the convention from the documentation: a factory function with defaults that can be overridden through options. We extend the context with a correlationId field so the handler can access it in a type-safe way.
// src/middlewares/correlation-id.ts import { randomUUID } from 'node:crypto'; import type { MiddlewareObj } from '@middy/core'; import type { APIGatewayProxyEventV2, APIGatewayProxyStructuredResultV2, Context, } from 'aws-lambda'; export type CorrelatedContext = Context & { correlationId: string }; interface Options { headerName?: string; } const defaults: Required<Options> = { headerName: 'x-correlation-id' }; export const correlationId = ( opts: Options = {}, ): MiddlewareObj< APIGatewayProxyEventV2, APIGatewayProxyStructuredResultV2, Error, CorrelatedContext > => { const { headerName } = { ...defaults, ...opts }; const setHeader = ( response: APIGatewayProxyStructuredResultV2 | null | undefined, id: string, ) => { if (!response) return; response.headers = { ...response.headers, [headerName]: id }; }; return { name: 'correlationId', before: (request) => { // header-normalizer has already lower-cased all header names const incoming = request.event.headers?.[headerName]; request.context.correlationId = incoming ?? randomUUID(); }, after: (request) => { setHeader(request.response, request.context.correlationId); }, onError: (request) => { // runs after http-error-handler, which has built the error response setHeader(request.response, request.context.correlationId); }, }; }; Note that the middleware sets the header in both after and onError. Without the second part, the error responses would be the ones missing an ID, and those are exactly the ones you need when debugging.
Step 3: Validation as a middleware
There are ready-made packages for validation, such as @middy/validator with JSON Schema. I deliberately show a hand-written version here, because it shows how little a middleware really is. It takes a check function that returns either the checked value or a list of problems. If there are problems, it throws an HTTP 400 error from the http-errors package. The error middleware takes care of the rest later.
// src/middlewares/validate-body.ts import createError from 'http-errors'; import type { MiddlewareObj } from '@middy/core'; export type Check<T> = (body: unknown) => { ok: true; value: T } | { ok: false; problems: string[] }; export const validateBody = <T>(check: Check<T>): MiddlewareObj<{ body?: unknown }> => ({ name: 'validateBody', before: (request) => { const result = check(request.event.body); if (!result.ok) { throw createError(400, JSON.stringify({ message: 'Invalid request', problems: result.problems })); } request.event.body = result.value; }, }); If you already use Zod, you can build the check function from a safeParse in one line. I described how that looks with Powertools Parser in Validate Lambda events with Powertools Parser and Zod.
Step 4: Put the handler together
Now everything comes together. The createLoan function contains only business logic and throws a 409 error for reference books. Middy builds the chain of five middlewares around it.
// src/handlers/create-loan.ts import middy from '@middy/core'; import httpErrorHandler from '@middy/http-error-handler'; import httpHeaderNormalizer from '@middy/http-header-normalizer'; import httpJsonBodyParser from '@middy/http-json-body-parser'; import createError from 'http-errors'; import { randomUUID } from 'node:crypto'; import type { APIGatewayProxyEventV2, APIGatewayProxyStructuredResultV2, } from 'aws-lambda'; import { correlationId, type CorrelatedContext } from '../middlewares/correlation-id.js'; import { validateBody, type Check } from '../middlewares/validate-body.js'; interface LoanRequest { bookId: string; memberId: string; days: number; } type LoanEvent = Omit<APIGatewayProxyEventV2, 'body'> & { body: LoanRequest }; const checkLoanRequest: Check<LoanRequest> = (body) => { const problems: string[] = []; const b = (body ?? {}) as Record<string, unknown>; if (typeof b.bookId !== 'string' || b.bookId.length === 0) problems.push('bookId is required'); if (typeof b.memberId !== 'string' || b.memberId.length === 0) problems.push('memberId is required'); if (!Number.isInteger(b.days) || (b.days as number) < 1 || (b.days as number) > 28) { problems.push('days must be a whole number between 1 and 28'); } return problems.length > 0 ? { ok: false, problems } : { ok: true, value: { bookId: b.bookId as string, memberId: b.memberId as string, days: b.days as number } }; }; // Pure business logic: no parsing, no error formatting, no headers const createLoan = async ( event: LoanEvent, context: CorrelatedContext, ): Promise<APIGatewayProxyStructuredResultV2> => { const { bookId, memberId, days } = event.body; if (bookId.startsWith('ref-')) { throw createError(409, 'Reference books cannot be borrowed'); } const dueDate = new Date(Date.now() + days * 24 * 60 * 60 * 1000).toISOString().slice(0, 10); console.log(JSON.stringify({ msg: 'loan created', correlationId: context.correlationId, bookId })); return { statusCode: 201, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ loanId: randomUUID(), bookId, memberId, dueDate }), }; }; export const handler = middy<LoanEvent, APIGatewayProxyStructuredResultV2, Error, CorrelatedContext>() .use(httpHeaderNormalizer()) .use(correlationId()) .use(httpErrorHandler({ fallbackMessage: 'Internal error' })) .use(httpJsonBodyParser()) .use(validateBody(checkLoanRequest)) .handler(createLoan); The order is no accident. The header normalizer sits on the outside so that all following middlewares see lowercase headers. Next comes the correlation ID, and only then httpErrorHandler. Because onError runs in reverse, the error handler builds the error response first, and then the correlation ID middleware adds its header. By the way, the JSON parser responds with 415 on its own if the content type does not match, and with 422 for broken JSON.
The order in .use() decides when before, after and onError run.
Step 5: Test with Vitest
In the end, a Middy handler is a normal async function. So you can call it directly with a hand-built event, without an AWS account or emulator. We add getRemainingTimeInMillis to the context, because Middy uses the remaining time for its built-in timeout signal.
// test/create-loan.test.ts import { describe, expect, it, vi } from 'vitest'; import type { APIGatewayProxyEventV2, Context } from 'aws-lambda'; import { handler } from '../src/handlers/create-loan.js'; const event = (body: unknown, headers: Record<string, string> = {}) => ({ headers: { 'Content-Type': 'application/json', ...headers }, body: typeof body === 'string' ? body : JSON.stringify(body), isBase64Encoded: false, }) as unknown as APIGatewayProxyEventV2; const context = { getRemainingTimeInMillis: () => 3000 } as unknown as Context; // The handler is typed with the parsed body; tests send the raw API Gateway event const invoke = (e: APIGatewayProxyEventV2) => (handler as unknown as (e: unknown, c: Context) => Promise<any>)(e, context); vi.spyOn(console, 'log').mockImplementation(() => {}); vi.spyOn(console, 'error').mockImplementation(() => {}); describe('create loan', () => { it('creates a loan and returns 201', async () => { const res = await invoke(event({ bookId: 'b-42', memberId: 'm-7', days: 14 })); expect(res.statusCode).toBe(201); expect(JSON.parse(res.body).bookId).toBe('b-42'); expect(res.headers['x-correlation-id']).toMatch(/^[0-9a-f-]{36}$/); }); it('reuses an incoming correlation id', async () => { const res = await invoke(event({ bookId: 'b-42', memberId: 'm-7', days: 7 }, { 'X-Correlation-Id': 'abc-123' })); expect(res.headers['x-correlation-id']).toBe('abc-123'); }); it('returns 400 with all problems for an invalid body', async () => { const res = await invoke(event({ bookId: '', days: 40 })); expect(res.statusCode).toBe(400); expect(JSON.parse(res.body).problems).toHaveLength(3); expect(res.headers['x-correlation-id']).toBeDefined(); }); it('returns 415 for a wrong content type', async () => { const res = await invoke(event('hello', { 'Content-Type': 'text/plain' })); expect(res.statusCode).toBe(415); }); it('returns 409 for reference books', async () => { const res = await invoke(event({ bookId: 'ref-1', memberId: 'm-7', days: Source:https://dev.to/sascha-ms/middy-middleware-for-aws-lambda-in-typescript-g8pRelated posts

