Skip to content

How to order middleware

Auth before logging, logging before tracing, tracing before rate limiting; a middleware that fails must not leave the response half-written.

Ordering middleware that works

  1. Auth before anything expensive

    Reject unauthenticated requests at the top. Logging an auth failure is fine; hashing a body is not.

  2. Tracing before rate limiting

    A rate-limited request should still be traced, so you can see the throttle in the trace.

  3. Rate limiting before the handler

    The handler should never run for a throttled request.

  4. The order on the way back is reversed

    Middlewares see the response in reverse order. If middleware A wraps middleware B, A's "after" code runs last.