Custom Request Headers
What you'll learn: How adding a custom HTTP header to legitimate requests can stop CSRF attacks that rely solely on automatic browser behavior.
The Core Idea
CSRF attacks work because browsers automatically attach cookies to requests—even those triggered by malicious sites. However, browsers have a critical limitation: JavaScript on an attacker's site cannot force the browser to send custom HTTP headers in a simple cross-origin request without triggering a CORS preflight check.
You can exploit this limitation by requiring all state-changing requests to include a custom header (like X-CSRF-Protection: true). Since attackers can't add this header from their domain without passing CORS checks (which your server won't allow), their forged requests will fail.
How It Works
Think of custom headers like a secret handshake. Your legitimate application (JavaScript running on your domain) can perform the handshake by adding the custom header:
POST /account/transfer
Host: yourbank.com
Cookie: session=abc123
X-CSRF-Protection: verify
An attacker's forged form or link cannot add X-CSRF-Protection because:
- HTML forms only send standard headers
- Cross-origin
fetch()orXMLHttpRequestwith custom headers requires a CORS preflight - Your server (correctly configured) won't grant CORS permission to attacker domains
Your server validates that the custom header is present before processing any sensitive action. Missing header? Reject the request.
Why This Works
Custom headers leverage the browser's built-in CORS protection. The attacker is stuck: they can trigger requests, but can't include the required header without your server's explicit permission—which you'll never grant to malicious origins.
Key Takeaway:
Requiring a custom HTTP header on state-changing requests prevents CSRF by relying on CORS restrictions that attackers cannot bypass from cross-origin contexts.