Double Submit Cookie Pattern
What you'll learn: You'll learn how to defend against CSRF attacks using a stateless mechanism that validates matching random tokens in both a cookie and a request parameter.
The Core Idea
The Double Submit Cookie Pattern is a stateless CSRF protection technique that doesn't require server-side session storage. Here's how it works:
When a user first visits your site, the server generates a random, cryptographically secure token and sets it as a cookie. Your frontend JavaScript then reads this cookie value and includes it as a request parameter (or custom header) when making state-changing requests. The server validates that both the cookie value and the parameter value match.
Why This Works
Think of it like a split key system at a bank vault: you hold one half of the key (the cookie), and you must present the other matching half (the request parameter) to open the vault.
An attacker performing CSRF can't read your cookies due to the Same-Origin Policy—they can only cause your browser to send them automatically. Since they can't read the cookie, they can't include the matching value in the request parameter. The request fails validation.
Implementation Pattern
- Server sets a random token in a cookie (e.g.,
csrf_token=abc123) - Frontend reads the cookie and includes it in POST requests (e.g., form field or header with value
abc123) - Server compares: does
cookie.csrf_token === request.parameter.csrf_token? - If they match, the request is legitimate
This is "stateless" because the server doesn't need to store valid tokens—it just compares the two submitted values.
Key Takeaway: The Double Submit Cookie Pattern provides CSRF protection without server-side state by requiring attackers to know a cookie value they cannot read, validated by matching it against a submitted parameter.