Skip to content

docs: clarify router-agnostic middleware runs after route resolution - #1088

Open
stareezy-1 wants to merge 1 commit into
danielgtaylor:mainfrom
stareezy-1:fix/933-middleware-before-routing
Open

docs: clarify router-agnostic middleware runs after route resolution#1088
stareezy-1 wants to merge 1 commit into
danielgtaylor:mainfrom
stareezy-1:fix/933-middleware-before-routing

Conversation

@stareezy-1

@stareezy-1 stareezy-1 commented Aug 5, 2026

Copy link
Copy Markdown

Summary

Fixes #933

Problem

The UseMiddleware doc comment claims the middleware stack executes before route matching:

The middleware stack for any API will execute before searching for a matching route to a specific handler, which provides opportunity to respond early...

This is not what happens. Router-agnostic middleware runs inside the matched operation handler chain (api.Middlewares().Handler(...)), so the adapter router resolves the route first. An unmatched request is answered by the router with a 404 and never enters the middleware chain:

GET /unmatched  →  404, middleware not called
GET /matched    →  middleware chain runs, then the handler

Why docs and not a behavior change: middleware receives a huma.Context bound to the matched operation (ctx.Operation()), which cannot exist before route resolution. Moving the chain before routing would require a context redesign across all adapters. Router-specific middleware is the supported way to run pre-routing logic (see the middleware docs).

Fix

  1. Correct the UseMiddleware doc comment to describe the actual behavior: the stack runs after the adapter router matches the request to a registered operation, and unmatched requests do not pass through it.
  2. Add a regression test locking in the behavior.

Tests

TestMiddlewareDoesNotRunForUnmatchedRoute added to huma_test.go:

Case Verifies
GET /unmatched router answers 404, middleware flag stays false
GET /matched middleware runs and the handler executes

All existing tests continue to pass (go test -race ./...).

The UseMiddleware doc comment claimed the middleware stack executes
before route matching, but the stack runs inside the matched operation's
handler chain: the adapter's router resolves the route first, so
unmatched requests (404) never enter it. Correct the comment and add a
test locking in the actual behavior (issue danielgtaylor#933).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

huma middleware is not executed before route resolution

1 participant