Documentation
Docs
Introduction
Getting Started
Tutorial: build an app
Core Concepts
Routing
Server-Side Rendering
Mimir, state management
Pages & Layouts
API Routes
Styling & Theming
Building & Deploying
API Reference
Guides
Recipes
FAQ (use cases)
csrf()
Stop cross-site request forgery on cookie-authenticated, state-changing requests with a rotating token.
Use case
When your app authenticates with cookies, the browser sends those cookies on requests another site triggers too, so a malicious page can make a write to your API as the logged-in user. A CSRF token, which the attacker cannot read or guess, proves the request came from your own page.
How it works
Safe methods (GET, HEAD, OPTIONS) receive a fresh token in the X-CSRF-Token response header.
Unsafe methods (POST, PUT, DELETE, ...) must echo a valid token back in the request header. The token is
compared in constant time (no timing leak) and rotates on each successful check. A missing or invalid
token replies 403. Tokens are keyed by req.sessionId (or req.ip as a fallback), so set a session id for
proper per-user tokens.
Configuration
| Option | Default | Notes |
|---|---|---|
header | "x-csrf-token" | The request header carrying the token. |
Example
Client flow: read X-CSRF-Token from a GET response, then send it as the configured header on the next
POST/PUT/DELETE:
Notes
CSRF only matters with cookie auth. If your API authenticates with a
Bearertoken in theAuthorizationheader (not auto-sent cross-site), CSRF does not apply and you can skip this middleware.
Next: requestId.