Routing and middleware

Write request context middleware

Create one typed middleware that validates an incoming request id or generates a safe one.

9 minute lesson

~~~

The middleware accepts a bounded valid correlation id or creates one, stores it in context, and returns it in the response. This is a small part of a typed bookmarks API built with Hono, tested in memory, and deployed once to Node and once to Cloudflare Workers, but the boundary it creates affects everything that follows.

Good custom middleware has one responsibility, explicit inputs, predictable output, and no hidden global state. The useful target is not encyclopedic coverage. Make one deliberate choice, observe its consequences, and know which requirement would make you revise it.

Watch for one shortcut in particular: trying to copy arbitrary unbounded header input into logs and responses. It makes later failures harder to locate. Instead, validate and bound the value, generate a fallback, type the context variable, and test both branches. Prefer an implementation you can explain from the outside before optimizing it.

Keep the wider goal in view: Compose routes and middleware so the request path stays short, typed, and visible. A short observation with concrete evidence is more useful than a confident sentence with no reproduction path.

Send missing, valid, oversized, and malformed ids and verify context, response header, and logs. Hand the result to someone else and see whether the behavior is clear without an oral explanation.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →