Skip to content
jshacks.dev
Security

Add CSRF protection with a double submit token

Protect a form from cross-site requests by comparing a random token in a cookie with the same token in the request body, using timingSafeEqual.

1 min read
Summarize in AI

A double-submit token works without server-side storage: you set a random value in a cookie and also put it in a hidden form field. An attacker's page can make the browser send the cookie but cannot read it to copy it into the form.

csrf.jsJavaScript
import { randomBytes, timingSafeEqual } from 'node:crypto';

export function issueToken(res) {
  const token = randomBytes(32).toString('hex');
  res.cookie('csrf', token, { sameSite: 'lax', secure: true });
  return token;
}

export function checkToken(req) {
  const a = Buffer.from(String(req.cookies.csrf ?? ''));
  const b = Buffer.from(String(req.body._csrf ?? ''));
  return a.length > 0 && a.length === b.length && timingSafeEqual(a, b);
}

Render the value from issueToken into <input type="hidden" name="_csrf">, and reject any POST for which checkToken returns false. The cookie is deliberately not HttpOnly here only if your page script must read it for fetch requests; for plain forms you can add httpOnly: true. timingSafeEqual throws on different lengths, hence the length check first. See the OWASP CSRF cheat sheet.

Plain double submit is weak when a sibling subdomain can set cookies, so sign the token with a server secret if that applies to you. It also needs cookie-parser and express.urlencoded before the route.

Share

More snippets

Security

Report CSP violations to an endpoint

Receive Content Security Policy violation reports at an endpoint with the report-to and report-uri directives, and parse what the browser sends.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.