DEV Community

Cover image for Middy middleware for AWS Lambda in TypeScript
Sascha Mirow-Stanitzok
Sascha Mirow-Stanitzok

Posted on Originally published at sascha-ms.de

Middy middleware for AWS Lambda in TypeScript

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
Enter fullscreen mode Exit fullscreen mode
{
  "compilerOptions": {
    "target": "ES2023",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "types": ["node"]
  },
  "include": ["src", "test"]
}
Enter fullscreen mode Exit fullscreen mode

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);
    },
  };
};
Enter fullscreen mode Exit fullscreen mode

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;
  },
});
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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.

Diagram: five Middy middlewares in .use() order, next to the execution of before, handler, after and onError in reverse

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: 7 }));
    expect(res.statusCode).toBe(409);
    expect(res.body).toBe('Reference books cannot be borrowed');
  });
});
Enter fullscreen mode Exit fullscreen mode

You can make the onion effect itself visible with a second, small test. It records which phase runs when, and it also shows what happens with an early response:

// test/order.test.ts
import { expect, it } from 'vitest';
import middy from '@middy/core';

const trace = (log: string[], name: string) => ({
  before: () => { log.push(`${name}.before`); },
  after: () => { log.push(`${name}.after`); },
});

it('runs middlewares like an onion', async () => {
  const log: string[] = [];
  const handler = middy(async () => { log.push('handler'); return 'ok'; })
    .use(trace(log, 'A'))
    .use(trace(log, 'B'));
  await handler({}, {} as any);
  expect(log).toEqual(['A.before', 'B.before', 'handler', 'B.after', 'A.after']);
});

it('skips the handler and every after hook on an early return', async () => {
  const log: string[] = [];
  const handler = middy(async () => { log.push('handler'); return 'ok'; })
    .use(trace(log, 'A'))
    .use({ before: () => ({ statusCode: 503, body: 'maintenance' }) })
    .use(trace(log, 'B'));
  const res = await handler({}, {} as any);
  expect(res).toEqual({ statusCode: 503, body: 'maintenance' });
  expect(log).toEqual(['A.before']);
});
Enter fullscreen mode Exit fullscreen mode
npx tsc --noEmit
npx vitest run
Enter fullscreen mode Exit fullscreen mode

Expected result: two test files, seven green tests. You will find more on testing Serverless projects in Testing the Serverless Framework with Vitest.

Step 6: Deploy with the Serverless Framework

Serverless Framework v4 builds TypeScript handlers itself with esbuild during deployment, so you do not need a plugin. Because our package.json contains "type": "module", it produces ES modules automatically. As a result, the configuration stays short:

# serverless.yml
service: library-loans
frameworkVersion: '4'

provider:
  name: aws
  runtime: nodejs24.x
  architecture: arm64
  region: eu-central-1
  memorySize: 512
  timeout: 10
  logRetentionInDays: 14

build:
  esbuild:
    bundle: true
    minify: false

functions:
  createLoan:
    handler: src/handlers/create-loan.handler
    events:
      - httpApi:
          path: /loans
          method: post
Enter fullscreen mode Exit fullscreen mode
serverless deploy
# use the URL printed as "endpoint"
curl -i -X POST "$API_URL/loans" -H "content-type: application/json" -d '{"bookId":"b-42","memberId":"m-7","days":14}'
curl -i -X POST "$API_URL/loans" -H "content-type: application/json" -d '{"bookId":"","days":40}'
Enter fullscreen mode Exit fullscreen mode

The first request should return status 201 with an x-correlation-id header, the second one 400 with a list of all three problems in the body. Within the free tier, this costs practically nothing. Still, clean up with serverless remove when you are done.

Common mistakes with Middy middleware

Most problems with Middy come from the order of the middlewares. These four cases show up most often.

The error handler is in the wrong place

If you register httpErrorHandler before the correlation ID middleware, its onError runs first. At that point there is no response yet that it could add a header to. Result: success responses have an ID, error responses do not. Try both variants in a test: the difference is exactly this one missing header. Rule of thumb: middlewares that want to change a finished error response belong before the error handler.

An early response skips all after phases

If a before function returns a value, the chain ends immediately. That includes the after functions of the outer layers. For example, if you build a maintenance mode as a middleware, its 503 response will lack the correlation ID unless you set the header there yourself. The test above shows this: after the early response, the log only contains A.before.

Internal error messages reach the client

Here Middy is pleasantly careful. The error handler only exposes messages of errors with a status code below 500. A plain Error object saying “database password wrong” turns into a neutral 500 response. Without fallbackMessage, however, its body stays empty, which is why I always set the option. The actual message ends up in CloudWatch through the logger.

Too many middlewares per function

Every middleware is another package in the bundle and another step per invocation. The core is small, but ten middlewares for a function with three lines of logic are a warning sign. Measure the Init Duration in the CloudWatch logs before and after you add something. How much time buffer a function needs overall is covered in Lambda timeout budget: from API Gateway to SDK.

Middy or Powertools, or both?

This question comes up almost every time, and luckily the answer is simple: you do not have to choose. Powertools for AWS Lambda provides logging, metrics, tracing and idempotency, and for TypeScript these tools ship their own Middy middlewares. Middy is the frame, and Powertools provides some of the best layers for it, which you plug in with .use() like any other Middy middleware. I show how to add Logger, Metrics and Tracer in Lambda Powertools TypeScript: logs, metrics, traces.

I would skip Middy for very small functions that only pass an SQS event along. A plain handler with a try/catch is often enough there. But as soon as a function talks over HTTP to people or other teams, the consistent frame pays off.

My take

What I like about Middy middleware is how little magic it contains. The core is a loop over three lists, and you can read all of it in an afternoon. That is precisely why the library works well for teams: nobody has to trust a framework blindly, and custom middlewares are quick to write.

Where I push back is the reflex to put everything into middlewares. Business rules like “reference books cannot be borrowed” belong in the handler, not in a layer in front of it. Middlewares are for the technical parts that are identical in every function. If you start naming middlewares after business terms, that is a good moment to pause. My suggestion for teams: a small shared base chain in its own package that every HTTP function uses, and beyond that only what the individual function really needs.

FAQ

Which Node.js version does Middy 7 need?

Middy 7 requires Node.js 22 or newer, and the maintainers recommend Node.js 24. On Lambda, use the nodejs24.x runtime for that. Node.js 20 is no longer supported as of version 7.

Can I use Middy with CommonJS?

Middy is published as ES modules only. If you bundle your code with esbuild, as Serverless Framework v4 or NodejsFunction in AWS CDK do, it also works with a CommonJS bundle. Without a bundler, you should switch to ES modules.

How do I test a single Middy middleware?

The easiest way is a mini handler: middy(async () => 'ok').use(myMiddleware()), then call that handler with a hand-built event. Alternatively, call before, after or onError directly with a request object you build yourself.

Does Middy also work with SQS or EventBridge?

Yes. Middy is not limited to HTTP; only some packages, such as the JSON body parser or the HTTP error handler, are meant specifically for API Gateway. For SQS, for example, there is a middleware for partially failed batches.

Your next step

Take one of your existing HTTP handlers and mark every line that has nothing to do with business logic. Usually surprisingly few lines remain. Then start by moving only the error handling into a Middy middleware like httpErrorHandler, and write a test that checks a 400 and a 500 response. Which cross-cutting concern do you still copy from handler to handler in your Lambda functions today? Feel free to share it in the comments.

All code from this article, ready to run: smirowstanitzok/sascha-ms-examples

Sources

This post was created with AI assistance.


👉 Next step: Curious what your own Lambda functions cost? Try my Lambda cost calculator – it runs right in your browser.

📬 Stay updated: New articles on serverless, AI and leading tech teams via RSS, browser push or the weekly newsletter (in German).

Originally published on sascha-ms.de. More articles on serverless, AI in everyday development and leading tech teams: sascha-ms.de/en

Top comments (0)