Skip to content

CSRF Protection ​

Introduction ​

Cross-site request forgery tricks a signed in user's browser into sending a state-changing request to your application from another site. Plinth defends against this with a per-session token. Every request that is not a GET, HEAD or OPTIONS must carry that token, otherwise the application responds 419 and your handler never runs.

CSRF protection lives in @plinthjs/session and builds on the session, so the session middleware must run first.

bash
pnpm add @plinthjs/session

Enabling protection ​

Add startSession() and then verifyCsrfToken() to the kernel's global middleware. Order matters: the CSRF middleware throws a 500 if no session was started.

ts
import { HttpKernel, Router } from '@plinthjs/http'
import { arraySession, startSession, verifyCsrfToken } from '@plinthjs/session'

const { manager } = arraySession() // any SessionManager works, see Session
const router = new Router()

const kernel = new HttpKernel(router, {
  middleware: [startSession(manager), verifyCsrfToken()],
})

The scaffolded web application already does this in src/server.ts, between the security headers and the middleware that attaches the current user.

The token ​

Each session has one CSRF token, minted lazily the first time it is read. Read it with session(req).token():

ts
import { session } from '@plinthjs/session'

router.get('/form', (req) => ({ csrf: session(req).token() }))

Tokens are 30 random bytes encoded as URL-safe base64, about 40 characters. Comparison is constant time. Call session(req).regenerateToken() to rotate the token, which session.regenerate() also does.

Sending the token ​

The middleware accepts the token from any of these places, in this order: the _token input field, the X-CSRF-TOKEN header, then the X-XSRF-TOKEN header.

HTML forms ​

Render the token in a hidden _token field. In a scaffolded application the view helper passes it to templates as csrf.

html
<form method="POST" action="/posts">
  <input type="hidden" name="_token" value="THE_TOKEN" />
  <!-- fields -->
</form>

The field works for URL-encoded bodies, JSON bodies and multipart forms, since the middleware reads it with req.input('_token').

JavaScript and single page apps ​

By default the middleware also publishes the token in a readable cookie named XSRF-TOKEN on every response. Client libraries such as axios read that cookie and echo it back in an X-XSRF-TOKEN header automatically, which satisfies the check. With fetch you do it yourself:

ts
// in the browser
const token = document.cookie
  .split('; ')
  .find((c) => c.startsWith('XSRF-TOKEN='))
  ?.split('=')[1]

await fetch('/posts', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', 'X-XSRF-TOKEN': decodeURIComponent(token ?? '') },
  body: JSON.stringify({ title: 'Hello' }),
  credentials: 'same-origin',
})

If you would rather embed the token in the page, for example in a meta tag, send it as X-CSRF-TOKEN.

Configuration ​

verifyCsrfToken(options) accepts:

ts
verifyCsrfToken({
  cookie: true, // publish the XSRF-TOKEN cookie (default true)
  cookieName: 'XSRF-TOKEN', // name of that cookie
  except: ['webhooks/*'], // paths exempt from verification
  secure: true, // Secure flag on the cookie
  sameSite: 'Lax', // 'Lax' (default) | 'Strict' | 'None'
  path: '/',
  domain: 'example.com',
})

The scaffolded web app passes { cookie: false }, because its pages are server rendered and receive the token as a form field, so no readable cookie is needed. Leave the cookie on for SPAs.

Excluding routes ​

Webhooks from third parties cannot know your token. Exempt their paths with except. Entries are matched against the request path with * wildcards, and a leading slash is optional:

ts
verifyCsrfToken({ except: ['webhooks/*', '/stripe/callback'] })

WARNING

An excluded path accepts state-changing requests from any site. Authenticate such endpoints another way, for example by verifying the sender's signature.

Stateless JSON APIs that authenticate with bearer tokens do not need CSRF protection at all, since browsers do not attach those tokens automatically. Simply leave verifyCsrfToken() out of the API stack. See API tokens.

Failures ​

A missing or wrong token throws an HttpException with status 419 and the message CSRF token mismatch.. The exception handler renders it as JSON for clients that want JSON, and as an HTML error page otherwise. Because the check runs before the handler, nothing in your route executes.

ts
import { Request } from '@plinthjs/http'

const res = await kernel.handle(new Request({ method: 'POST', url: '/posts' }))
res.status // => 419

Lower level helpers ​

generateToken() mints a token and verifyToken(a, b) compares two in constant time. They are exported if you need to build your own scheme.

ts
import { generateToken, verifyToken } from '@plinthjs/session'

const token = generateToken()
verifyToken(token, token) // => true

Released under the MIT License.