Middleware
Middleware intercepts requests before they reach guards and handlers. Learn the MiddlewareFn interface, built-in middlewares, and how to write custom middleware.
Middleware
Middleware runs before guards and intercepts requests. It can short-circuit the pipeline by writing a response directly, or call next() to continue.
The MiddlewareFn Interface
A middleware receives the request context and a next function. Call next() to pass control downstream; return without calling next() to short-circuit.
Writing Custom Middleware
Global Middleware
Apply middleware to every route in the application:
Controller-Level Middleware
Bind middleware to all handlers in a controller:
Handler-Level Middleware
Bind middleware to specific handlers:
Built-in Middlewares
CORS
Helmet
Sets security-related HTTP response headers:
Sets: X-Content-Type-Options, X-Frame-Options, X-XSS-Protection, Referrer-Policy, Content-Security-Policy, and others.
RequestLogger
Logs method, path, status code, latency, and request ID for each request:
Output example:
CSRF
Double-submit cookie pattern for CSRF protection on mutation endpoints:
The CSRF middleware:
- Issues a signed CSRF token as an HTTP-only cookie on safe requests (
GET,HEAD,OPTIONS). - Validates that the
X-CSRF-Tokenheader matches the cookie on mutation requests (POST,PUT,PATCH,DELETE).
Module-Level Middleware
Apply middleware only to routes within a specific module: