Security

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.

4 min readUpdated DocumentationEdit this page
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.

❯npm install @axiljs/security
❯pnpm add @axiljs/security
❯yarn add @axiljs/security
❯bun add @axiljs/security
TypeScript
TS
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:

  1. Reads the token cookie (_csrf by default). If there is none, it generates a new token (32 random bytes, hex encoded) and sends it with Set-Cookie.
  2. Puts the token on req.locals.csrfToken.
  3. Lets GET, HEAD and OPTIONS through without any check.
  4. For every other method, reads the token header (x-csrf-token by default) and compares it with the cookie in constant time (crypto.timingSafeEqual).
  5. On a missing or mismatched header, passes a ForbiddenError (HTTP 403, code FORBIDDEN) to the error handlers.
SituationResult
Safe method (GET, HEAD, OPTIONS)Allowed
Header missing403 CSRF token missing. Include x-csrf-token header.
Header does not match the cookie403 Invalid CSRF token.
Header matches the cookieAllowed

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

OptionTypeDefaultDescription
cookieNamestring'_csrf'Name of the token cookie
headerNamestring'x-csrf-token'Header the client sends the token in. Matched case-insensitively
cookie.securebooleantrue when NODE_ENV=production, otherwise falseAdd the Secure attribute (HTTPS only)
cookie.sameSite'strict' | 'lax' | 'none''strict'SameSite attribute
cookie.pathstring'/'Path attribute
TypeScript
TS
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:

TypeScript
TS
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):

TypeScript
TS
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.

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY