DEV Community

Cover image for Stop copying Lambda boilerplate: the Middy onion model explained
Sascha Mirow-Stanitzok
Sascha Mirow-Stanitzok

Posted on Edited on Originally published at sascha-ms.de

Stop copying Lambda boilerplate: the Middy onion model explained

In a code review not long ago I opened three Lambda handlers from the same team, side by side. All three parsed the JSON body, checked a few headers, validated input and turned errors into HTTP responses. All three did it slightly differently. One returned errors as plain text, one as JSON, and one forgot the correlation ID on failures. Nobody had done anything wrong; they had just copied and adjusted the same 30 lines of boilerplate.

That is the problem Middy solves for me. I walk through a complete example, a small library API where members borrow books, in Middy middleware for AWS Lambda in TypeScript. This post covers the ideas that matter most.

A frame around the handler

Lambda gives you an event and a context and expects a result. There is no built-in place for cross-cutting concerns like logging, validation or error formatting. Middy adds that place. It is an open-source library built only for Lambda, with a tiny core (@middy/core) and separate packages you install as needed. Version 7 requires Node.js 22 or newer, and Node.js 24 is recommended.

A middleware is just an object with up to three functions: before, after and onError. All of them receive the same request with event, context, response and error. Writing your own is surprisingly little code. A body validator, for example, can be this small:

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({ problems: result.problems }));
    }
    request.event.body = result.value;
  },
});
Enter fullscreen mode Exit fullscreen mode

The handler that remains only contains business logic, like refusing to lend reference books. And because a Middy handler is still a plain async function, you can test it with Vitest and a hand-built event, no AWS account needed.

Order is everything

The single most important thing to understand is the onion model. before functions run in the order you register them with .use(). after and onError run in reverse. Whoever goes in first comes out last.

This has very practical consequences. In my example, a correlation ID middleware adds an x-correlation-id header to every response. If it is registered after httpErrorHandler, its onError runs before the error response exists, and failed requests end up without an ID, which are exactly the ones you need when debugging. Registered before the error handler, everything lines up.

The second trap: a before function can return a value to end the chain early, handy for caches or a maintenance mode. But that skips the handler and every after function of the outer layers too. Your 503 maintenance response will silently lack headers that other middlewares would normally add.

Where I draw the line

Middy is pleasantly careful about errors: the HTTP error handler only exposes messages for status codes below 500, so an internal error does not leak details to the client. I always set fallbackMessage, though, so a 500 has a meaningful body.

I also push back on putting everything into middlewares. Business rules belong in the handler. Middlewares are for the technical parts that are identical across functions. Every middleware is another package in the bundle and another step per invocation, so ten layers around three lines of logic are a warning sign. And Middy versus Powertools is not an either-or: Powertools for TypeScript ships its own Middy middlewares for logging, metrics and tracing, so they slot right into the same chain.

My recommendation for teams: a small shared base chain that every HTTP function uses, plus only what each function really needs.

What the full article covers

  • A step-by-step project setup with ES modules, NodeNext and the right Middy packages
  • Two custom typed middlewares for correlation IDs and validation
  • The full handler with five middlewares and why they sit in exactly that order
  • Vitest tests, including one that makes the onion order and early returns visible
  • Deployment with Serverless Framework v4 on nodejs24.x, plus common mistakes and an FAQ

Read it here: Middy middleware for AWS Lambda in TypeScript

๐Ÿ“– This is the condensed version. The full article on sascha-ms.de goes deeper โ€“ with all code samples, diagrams and a short knowledge check.


๐Ÿ‘‰ 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)