Skip to main content

Middleware

Middleware sits between the incoming request and your route handler. It can inspect requests, modify responses, short-circuit the chain, or add cross-cutting behavior like logging, auth, and caching.

How Middleware Works

Each middleware calls next(request) to pass control to the next middleware (or the handler). It can act before and/or after the call.

The Protocol

PrismMiddleware

Writing Custom Middleware

Before-only (modify request)

Request Timer

After-only (modify response)

Security Headers

Before and after (wrap)

Timing Middleware

Short-circuit (block request)

Maintenance Mode

Registering Middleware

Global Middleware

Applied to every request:
Global

Group Middleware

Applied only to routes in the group:
Group-specific

Execution Order

Middleware runs in the order you register it:
Order Matters
Put error-handling middleware first so it catches errors from all other middleware and handlers. Put auth middleware before business logic middleware.

Composing Middleware

Build powerful processing pipelines by stacking middleware:
Production Stack

Real-World Example: API Key Auth

API Key Middleware

Built-in Middleware

Explore CORS, auth, rate limiting, and more.

Lifecycle Hooks

Fine-grained request/response/error hooks.