What is middleware?
Middleware sits between the incoming request and your handler. It can:- Run code before the handler (check auth, log start time)
- Run code after the handler (log duration, add headers)
- Short-circuit the request (reject unauthorized users)
- Modify the request or response
The middleware signature
A middleware is a function that takes a handler and returns a new handler:Applying middleware
Global middleware
Apply to all routes withapp.Use():
Scoped middleware
Apply to specific routes withapp.With():
Group middleware
Apply to a group of routes:Execution order
Middleware runs in the order you add them. For the chainA → B → C → handler:
Abefore →Bbefore →Cbefore →handlerhandlerreturnsCafter →Bafter →Aafter
Writing middleware
Authentication middleware
CORS middleware
Recovery middleware
Middleware with configuration
Use the options pattern for configurable middleware:Passing data between middleware
Use Go’s context to pass data from middleware to handlers:Using net/http middleware
Mizu can use standardnet/http middleware via Compat.Use():
Common patterns
Skip paths
Don’t run middleware on certain paths:Summary
Next steps
Error Handling
Handle errors in middleware.
Logging
Add logging middleware.