What is CSRF?

CSRF (Cross-Site Request Forgery) is an attack where a malicious site makes the user's browser send an authenticated request to your site, riding on cookies the browser attaches automatically, so actions happen as the user without their intent.

How it works

  1. The user is logged in to bank.example with a session cookie.
  2. They visit evil.example, which contains a hidden auto-submitting form that POSTs to bank.example/transfer.
  3. The browser includes the bank's cookies, and the bank sees a legitimate-looking, authenticated request.

The attacker cannot read the response (the same-origin policy blocks that), but the state-changing action has already happened.

Defences

  1. SameSite cookies: Lax (the default in modern browsers) stops cookies on cross-site POSTs and sub-requests; Strict stops them on all cross-site requests. This blocks most CSRF on its own.
  2. CSRF tokens: a random, per-session (or per-form) token included in forms or headers that the attacker cannot know. The server rejects requests without a matching token. Double-submit cookie and synchroniser token patterns are common.
  3. Check Origin / Sec-Fetch-Site headers on state-changing requests and reject cross-site ones.
  4. Never change state with GET requests: GET must be safe to repeat.
  5. Custom headers for APIs: browsers do not let cross-site forms add headers like X-Requested-With without a CORS preflight.
  6. Re-authenticate for critical actions (password change, payments).

Frameworks

Many frameworks include CSRF protection. Next.js Server Actions only accept POST and compare the Origin header with the host, which protects against CSRF by default.

CSRF vs XSS

XSS runs attacker code in your origin, which defeats CSRF defences. Fix XSS first.

Code example

js
1// Express-style middleware (server side) showing layered CSRF defences
2import crypto from "node:crypto";
3
4const ALLOWED_ORIGINS = new Set(["https://app.example.com"]);
5
6export function issueCsrfToken(req, res) {
7 const token = crypto.randomBytes(32).toString("hex");
8 req.session.csrfToken = token; // stored server-side with the session
9 res.cookie("session", req.session.id, { httpOnly: true, secure: true, sameSite: "lax" });
10 return token; // embed in a hidden form field or send to the SPA
11}
12
13export function csrfProtection(req, res, next) {
14 if (["GET", "HEAD", "OPTIONS"].includes(req.method)) return next(); // GETs must not change state
15
16 // 1. Reject cross-site requests by origin
17 const origin = req.get("origin");
18 if (origin && !ALLOWED_ORIGINS.has(origin)) return res.status(403).send("Bad origin");
19 if (req.get("sec-fetch-site") === "cross-site") return res.status(403).send("Cross-site request");
20
21 // 2. Require a token the attacker can't know (timing-safe comparison)
22 const sent = Buffer.from(String(req.get("x-csrf-token") ?? req.body?._csrf ?? ""));
23 const expected = Buffer.from(String(req.session.csrfToken ?? ""));
24 if (sent.length !== expected.length || !crypto.timingSafeEqual(sent, expected)) {
25 return res.status(403).send("Invalid CSRF token");
26 }
27 next();
28}
29
30// Client: fetch("/transfer", { method: "POST", headers: { "x-csrf-token": token }, body })

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app