Skip to main content

Lifecycle Hooks

While middleware wraps the entire request/response cycle, hooks let you tap into specific moments: before the request is handled, after the response is built, or when an error occurs.

The Three Hook Types

Setup

Register Hooks

Real-World: Error Monitoring

Send errors to an external service:
Error Tracking

Real-World: Request Sanitization

Clean up incoming data before it reaches handlers:
Sanitize Input

Multiple Hooks

Register multiple hooks of the same type — they run in order:
Hook Chain
Hooks are lighter than middleware when you only need to act at one specific point in the lifecycle. Use middleware when you need to wrap the entire request/response flow (e.g., timing, caching).

Middleware

Full middleware pipeline for wrapping requests.

Tracing

Request tracing with correlation IDs.