Skip to main content
Middleware wraps handlers to add behavior before or after request processing. They’re perfect for cross-cutting concerns like logging, authentication, and error recovery that apply to multiple routes.

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
Think of middleware as layers of an onion. Each request passes through each layer going in, hits your handler, then passes through each layer coming out.

The middleware signature

A middleware is a function that takes a handler and returns a new handler:
Here’s a simple logging middleware:

Applying middleware

Global middleware

Apply to all routes with app.Use():

Scoped middleware

Apply to specific routes with app.With():

Group middleware

Apply to a group of routes:

Execution order

Middleware runs in the order you add them. For the chain A β†’ B β†’ C β†’ handler:
Request flow:
  1. A before β†’ B before β†’ C before β†’ handler
  2. handler returns
  3. C after β†’ B after β†’ A after

Built-in middleware

Mizu includes one middleware by default:
The Logger middleware logs each request with method, path, status, and duration. Configure it:

Writing middleware

Basic middleware

Authentication middleware

CORS middleware

Recovery middleware

Note: Mizu has built-in panic recovery that passes panics to your error handler. This example shows the pattern.

Middleware with configuration

Use the options pattern for configurable middleware:
Usage:

Passing data between middleware

Use Go’s context to pass data from middleware to handlers:

Using net/http middleware

Mizu can use standard net/http middleware via Compat.Use():
This lets you use middleware from other Go libraries that follow the standard pattern.

Common patterns

Skip paths

Don’t run middleware on certain paths:

Conditional middleware

Apply middleware based on request:

Summary

Middleware keeps your handlers focused on business logic while handling cross-cutting concerns in reusable, composable functions.