Cross-site request forgery (CSRF)

Stop other websites from making your users' browsers perform actions they did not intend.

Intermediate30 min

Learning objectives

  • Explain how a CSRF attack uses a victim's existing session
  • Apply SameSite cookies and synchroniser tokens
  • Use Fetch Metadata headers as an additional check

The attack

Browsers attach cookies to requests automatically. Suppose a user is logged in to bank.example. They then visit an attacker’s page that contains:

<form action="https://bank.example/transfer" method="POST" id="f">
  <input type="hidden" name="to" value="attacker-account">
  <input type="hidden" name="amount" value="5000">
</form>
<script>document.getElementById('f').submit();</script>

The browser sends the form with the user’s session cookie. If the bank only checks the cookie, the transfer succeeds. The attacker never sees the response; they only need the action to happen.

Defence 1: SameSite cookies

The SameSite attribute tells the browser when to send a cookie on cross-site requests:

  • Strict: never sent cross-site. Safest, but can be inconvenient when users follow links into your site.
  • Lax: sent on top-level navigations with safe methods (such as GET), but not on cross-site form POSTs or background requests. A good default.
  • None: sent everywhere. Requires Secure. Avoid unless you need cross-site embedding.

SameSite=Lax blocks the attack above, but do not depend on it alone. Browsers and deployment setups differ, and sibling subdomains are considered same-site.

Defence 2: synchroniser tokens

Include a random token in each state-changing form and verify it on the server. An attacker’s page cannot read the token from your site, so it cannot forge a valid request.

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

// When rendering the form
if (!req.session.csrfToken) {
  req.session.csrfToken = randomBytes(32).toString('base64url');
}
// ...include req.session.csrfToken as a hidden field named _csrf

// When handling the POST
const given = Buffer.from(String(req.body._csrf ?? ''));
const expected = Buffer.from(req.session.csrfToken ?? '');

if (
  expected.length === 0 ||
  given.length !== expected.length ||
  !timingSafeEqual(given, expected)
) {
  return res.status(403).send('Invalid CSRF token');
}

The length checks matter. timingSafeEqual throws on mismatched lengths, and two empty buffers would compare equal, so a missing token must be rejected explicitly.

Defence 3: Fetch Metadata

Modern browsers send Sec-Fetch-Site with each request. For state-changing routes you can reject anything that did not originate from your own site:

const site = req.headers['sec-fetch-site'];
if (site && site !== 'same-origin' && site !== 'none') {
  return res.status(403).end();
}

Older browsers do not send this header, so treat it as an extra layer, not the only one.

Design rules that help

  • Never perform state changes with GET requests. Links, images and prefetching can trigger GET requests without user intent.
  • Require re-authentication or a confirmation step for high-impact actions such as changing an email address or transferring money.

Lab: test your own form

On a local app you control, submit a state-changing form from a second page served on a different port. Confirm the request is rejected once the token check is in place.

Key takeaways

  • CSRF abuses the browser’s automatic cookie handling. Your server must check that the request was intended.
  • Use SameSite=Lax or Strict on session cookies, plus synchroniser tokens for forms.
  • Keep state changes off GET requests.