How-To Guide

How to Implement CSRF Double-Submit Cookies

Issue a random token cookie, require the same value in a header or form field, compare in constant time, and layer SameSite on top.

On this page

  1. Introduction
  2. The attack and the invariant
  3. Issue the token cookie
  4. Verify on every state-changing request
  5. Layer SameSite cookies
  6. Test with hostile requests
  7. Common pitfalls
  8. Conclusion

Introduction

Cross-site request forgery exploits the browser’s most convenient feature: cookies are attached to requests automatically, regardless of which site initiated them. A user logged into a bank has a session cookie; a page the user visits on another origin can submit a form to the bank’s transfer endpoint, and the browser helpfully attaches the session cookie, making the forged request indistinguishable from a real one to any handler that only checks authentication. Every CSRF defense is a way to add something the attacker cannot supply. The synchronizer-token pattern stores per-session secrets server-side, which requires session storage. The double-submit pattern removes that storage requirement with a neat symmetry: the server sets a random value in a cookie, the client must echo the same value in a header or form field, and the attacker, unable to read cookies from another origin, cannot construct a request where both halves match. This tutorial implements the pattern properly, random generation, constant-time comparison, cookie scoping, the SameSite layer, and the tests that prove a cross-site form fails while the real application keeps working.

The attack and the invariant

The attacker’s capability set defines the defense. A malicious page can cause the victim’s browser to issue requests to any origin, with cookies attached, that is the attack. It cannot read responses cross-origin due to the same-origin policy, cannot read the victim’s cookies for the target origin, and cannot set arbitrary headers on form-initiated requests. The double-submit invariant exploits exactly this gap: a request is accepted only when a cookie value and a submitted value agree, where the submitted value travels in a place the attacker cannot populate without reading the cookie. A form the attacker hosts can carry the session cookie automatically, but the token field must be filled with the actual cookie value, which the attacker’s page cannot read, so any value it guesses will not match. The invariant holds as long as one rule is respected absolutely: the token must carry no meaning, it is a random echo, not a session identifier or an encrypted user id, because anything predictable or derivable collapses the security to the predictability of that derivation.

The cookie is set at session start and refreshed per session, not per request, which keeps the mechanism stateless. Generation must be cryptographic randomness, never a timestamp, a hash of the user id, or anything predictable, because the entire defense is the attacker’s inability to guess the value.

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

export function issueCsrfCookie(req, res, next) {
 if (!req.cookies.csrfToken) {
  res.cookie('csrfToken', randomBytes(16).toString('base64url'), {
   httpOnly: false,
   secure: true,
   sameSite: 'Strict',
   path: '/',
  });
 }
 next();
}

The httpOnly flag is deliberately false here, and the reasoning matters: the double-submit pattern needs client code to read the cookie value in order to echo it into a header, so the token cookie is not httpOnly, while the session cookie absolutely is. The token cookie contains no secret capability, only a random echo value, so its JavaScript readability is harmless by design. Keep the two cookies distinct in name and scope, and document the distinction, because a reviewer who sees httpOnly false on a cookie reflexively files it as a bug, and the design note is what turns that review into an approval.

Verify on every state-changing request

Verification is a middleware over the methods that change state, POST, PUT, PATCH, DELETE, comparing the cookie value and the submitted value in constant time.

const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);

export function requireCsrf(req, res, next) {
 if (SAFE_METHODS.has(req.method)) return next();
 const cookieToken = req.cookies.csrfToken;
 const submitted = req.get('x-csrf-token') ?? req.body?._csrf;
 if (!cookieToken || !submitted || !equalTokens(cookieToken, submitted)) {
  return res.status(403).json({ error: 'csrf_check_failed' });
 }
 next();
}

function equalTokens(a, b) {
 const bufA = Buffer.from(String(a));
 const bufB = Buffer.from(String(b));
 return bufA.length === bufB.length && timingSafeEqual(bufA, bufB);
}

Three details in this small function carry the security. Constant-time comparison prevents timing side channels from leaking how many leading bytes matched. Missing values fail closed, an absent cookie or absent submitted token is a rejection, never a pass. And the safe-method exemption applies only to genuinely safe handlers: a GET that mutates state, a search-that-saves, a link-that-archives, reopens the hole through the exempted door, so the state-changing-by-GET anti-pattern is banned by policy, and code review enforces what the middleware cannot see.

Layer SameSite cookies

SameSite is the modern first line of CSRF defense, and it composes with the token layer rather than competing with it. SameSite=Lax, the browser default in modern engines, sends cookies on same-site requests and top-level navigations, which blocks the classic cross-site POST while keeping normal link-following functional. SameSite=Strict withholds cookies even on top-level navigation from other sites, stronger, with a usability cost, users arriving from a link land logged-out-looking. The token layer covers what SameSite cannot: older browsers predating the default, edge cases around subdomains and site definitions, and any flow where a partner site legitimately posts cross-origin, which should be migrated to a same-site redirect flow or an explicit CORS-configured API with non-cookie authentication. Setting both layers, SameSite on every session cookie and the double-submit check on every mutation, is the recommended posture in OWASP’s guidance, defense in depth with each layer covering the other’s gaps.

Test with hostile requests

CSRF tests are adversarial by construction: the passing cases prove nothing unless the failing cases are also engineered. The happy path: issue the cookie, echo it in the header, and every method succeeds. The forged request: a POST with valid session cookies but a missing, wrong, or absent token must receive 403, and the wrong-token case should use a plausible near-miss, same length, one byte different, to catch comparison bugs that a wildly different value would hide. The cross-site simulation: a request originating from a hostile origin, which in integration terms means verifying the browser-level behavior with SameSite set, best done in Playwright or another real-browser harness that can navigate a hostile page and assert the request was sent without cookies. The safe-method discipline: a GET route that mutates state should not exist, and a lint or review check for mutation vocabulary in GET handlers, save, delete, update, enforces it mechanically. Regression on the timing comparison: assert the comparison function rejects same-length near-misses, which locks the constant-time implementation against well-meaning refactors to ordinary equality.

it('rejects a one-byte-off token', async () => {
 const res = await request(app)
  .post('/api/transfer')
  .set('Cookie', sessionCookie + '; csrfToken=' + token)
  .set('x-csrf-token', flipByte(token))
  .send({ to: 'attacker', cents: 100 });
 expect(res.status).toBe(403);
});

Common pitfalls

  • Meaningful tokens. A token derived from the user id or session is guessable; randomness is the entire defense, and predictability collapses it.
  • Failing open on absence. Missing cookie or missing header must reject; defaults that skip the check for unauthenticated requests leak the policy.
  • **Ordinary string comparison. ** Non-constant-time equality leaks prefix matches through timing; use timingSafeEqual or the platform equivalent.
  • State-changing GET routes. The safe-method exemption becomes a bypass; mutation vocabulary belongs behind the checked methods.
  • **httpOnly confusion. ** The token cookie must be readable to be echoed while the session cookie must not; mixing the two flags on the wrong cookies breaks one layer or the other.
  • **Token in a URL query. ** Tokens leak into referrers and logs; headers and hidden fields only.

Conclusion

CSRF is the browser attaching credentials to requests the user never made, and the double-submit pattern defeats it with an echo the attacker cannot produce: a cryptographically random cookie value that every state-changing request must repeat in a header or field, verified in constant time and failing closed on absence. Keep the token meaningless, keep the session cookie httpOnly while the token cookie is deliberately readable, and exempt only genuinely safe methods, which makes state-changing GET routes a policy violation rather than a bypass. Layer SameSite=Lax or Strict on session cookies as the modern first line, with the token covering legacy browsers and edge cases, and test adversarially, near-miss tokens, cross-site submissions in a real browser, so the failing cases are engineered rather than assumed. The pattern is stateless, cheap, and auditable, which is why it remains the default recommendation when synchronizer tokens would require storage the architecture does not have.

Sources: OWASP: CSRF prevention cheat sheet, MDN: Set-Cookie header, OWASP: session management cheat sheet.

FAQ

Why does the double-submit pattern work?
An attacker on another origin can cause the victim’s browser to send cookies automatically, but cannot read them, and therefore cannot learn the token value to echo in the header or field. Matching the two values proves the request came from code that could read the cookie, which is same-origin code.
Is SameSite enough on its own?
SameSite=Lax blocks the common cross-site POST case and is a strong default, but it is defense in depth, not a replacement: older browsers, subdomain attackers, and top-level GET navigation edge cases keep a token layer worth having.
Where do I put the token, a header or a form field?
A header suits JavaScript-driven APIs and fits middleware cleanly. A hidden form field suits classic server-rendered forms. Both work; pick one per surface and keep the comparison logic shared.

Related Examples