Middleware

The pipeline every request passes through, why its order is a correctness decision and not a style one, and how cross-cutting concerns compose without leaking into handlers.

The Middleware Pipeline

Middleware is function composition around a handler, with a phase on the way in and a phase on the way out — not a list of things that run first.

Q · What is middleware actually, once the framework's `next()` is taken away?
Middleware Ordering Is a Correctness Decision

The chain is a dependency graph flattened into a list; reordering it does not tidy the same behaviour, it produces different behaviour.

Q · Why does the same set of middleware behave differently when you change the order?
Authenticate First, or Rate-Limit First?

Authenticating first means an unauthenticated flood still costs you crypto and a user lookup; rate-limiting first means your key is an IP, which is coarse and evadable. Both are true, so you do both, with different keys.

Q · Should rate limiting run before or after authentication?
The Error Boundary

One place that turns any failure below it into a response the client can act on and a log line you can investigate — plus the specific failures it will not catch.

Q · When something below fails, what turns that into a response, and what decides which response?
Request Context Propagation

Getting the correlation id, principal, tenant and deadline from the outermost middleware to a log line five layers down — without an extra argument on every function, and without a global that lies.

Q · How does per-request state reach code deep in the call stack without being threaded through every signature?
What Belongs in the Pipeline

A concern belongs in middleware if it is uniform, transport-level, needed even when no handler runs, and cheap — which rules out several of the things most often put there.

Q · Which concerns belong in the middleware pipeline, and which ones only look like they do?