CSRF Protection
Block cross-site request forgery in a Node.js API with csrf() from @axiljs/security: a double-submit cookie, an x-csrf-token header and constant-time checks.
On this page6
csrf() protects cookie-authenticated routes from cross-site request forgery with the double-submit cookie pattern. The server sets a random token in a cookie that JavaScript can read; your frontend copies it into a request header; the middleware rejects any state-changing request where the header and the cookie do not match. A malicious site can make the browser send your cookies, but it cannot read them, so it cannot produce the header.
1import { Application } from '@axiljs/core'
2import { csrf } from '@axiljs/security'
3
4const app = new Application()
5app.use(csrf())How it works
On every request the middleware:
- Reads the token cookie (
_csrfby default). If there is none, it generates a new token (32 random bytes, hex encoded) and sends it withSet-Cookie. - Puts the token on
req.locals.csrfToken. - Lets
GET,HEADandOPTIONSthrough without any check. - For every other method, reads the token header (
x-csrf-tokenby default) and compares it with the cookie in constant time (crypto.timingSafeEqual). - On a missing or mismatched header, passes a
ForbiddenError(HTTP403, codeFORBIDDEN) to the error handlers.
| Situation | Result |
|---|---|
Safe method (GET, HEAD, OPTIONS) | Allowed |
| Header missing | 403 CSRF token missing. Include x-csrf-token header. |
| Header does not match the cookie | 403 Invalid CSRF token. |
| Header matches the cookie | Allowed |
The token stays the same for as long as the cookie exists. It is not rotated per request.
Note
An unsafe request that arrives with no cookie at all always fails: the middleware issues a new token and the header cannot match it. Make sure the client has made at least one GET (for example, loading the page or calling a /csrf endpoint) before its first POST.
Options
| Option | Type | Default | Description |
|---|---|---|---|
cookieName | string | '_csrf' | Name of the token cookie |
headerName | string | 'x-csrf-token' | Header the client sends the token in. Matched case-insensitively |
cookie.secure | boolean | true when NODE_ENV=production, otherwise false | Add the Secure attribute (HTTPS only) |
cookie.sameSite | 'strict' | 'lax' | 'none' | 'strict' | SameSite attribute |
cookie.path | string | '/' | Path attribute |
1app.use(csrf({
2 cookieName: 'XSRF-TOKEN',
3 headerName: 'X-XSRF-TOKEN',
4 cookie: { sameSite: 'lax', path: '/' }
5}))The cookie is written as _csrf=<token>; Path=/; SameSite=strict, plus ; Secure when enabled. It is a session cookie (no Max-Age or Expires) and deliberately not HttpOnly, because the frontend must read it. The forbidden-error message always names x-csrf-token, even when you change headerName.
XSRF-TOKEN / X-XSRF-TOKEN are the names Angular's HttpClient uses by default, so with the options above Angular sends the header without extra code.
Sending the token from the browser
Read the cookie and send it on every request that changes state:
1function csrfToken(): string {
2 return document.cookie
3 .split('; ')
4 .find((c) => c.startsWith('_csrf='))
5 ?.split('=')[1] ?? ''
6}
7
8await fetch('/api/orders', {
9 method: 'POST',
10 credentials: 'same-origin',
11 headers: { 'content-type': 'application/json', 'x-csrf-token': csrfToken() },
12 body: JSON.stringify({ sku: 'A1' })
13})Exposing the token from the server
Because the token is on req.locals.csrfToken, a safe route can return it, for clients that cannot read cookies directly (or that want to fetch the token up front):
app.get('/csrf', (req, res) => {
res.success({ token: req.locals.csrfToken })
})In server-rendered HTML, put req.locals.csrfToken in a <meta> tag and have your scripts send it as the header. Plain HTML form posts are not enough on their own: the middleware only reads the header, not a form field.
When you need it
CSRF matters when the browser attaches credentials automatically, which means cookie or session auth. APIs that authenticate with a bearer token in the Authorization header (see JWT) are not exposed to CSRF in the same way, because a cross-site page cannot set that header.
Tip
The middleware sets its cookie with res.header('Set-Cookie', ...), which replaces any Set-Cookie value already on the response. If another middleware also sets a cookie on the same request, register it after csrf() and append rather than overwrite.
Related
Was this page helpful?