Course contentsShow
← Web Development
Lesson 2912 of 2,98252. Frontend SecurityFree lesson

Double Submit Cookie Pattern

Implementing the double submit cookie technique where frontend reads and sends cookie values in headers.

Double Submit Cookie Pattern

You'll learn how to implement a CSRF defense where the frontend reads a cookie value and echoes it back in a custom header, letting the server verify both match.

What Is the Double Submit Cookie Pattern?

The double submit cookie pattern is a CSRF protection technique that works without server-side session state. The server sets a random token in a cookie (often HttpOnly: false so JavaScript can read it). When your frontend makes a state-changing request, it reads that cookie value and sends it again in a custom request header like X-CSRF-Token.

Why it works: An attacker's malicious site cannot read cookies from your domain (thanks to same-origin policy) and therefore cannot forge the custom header. The browser automatically sends cookies, but the attacker can't extract the value to duplicate it in the header.

How Frontend Implements It

  1. Read the cookie using document.cookie or a cookie utility
  2. Extract the CSRF token value (often named something like csrf_token)
  3. Attach it as a custom header in your fetch/axios requests

Analogy: Imagine a ticket booth gives you a wristband (cookie) and asks you to write the wristband number on a form (header). An outsider can't see your wristband number, so they can't fill out the form correctly.

// Example: Reading and sending the token
const csrfToken = getCookie('csrf_token');

fetch('/api/update-profile', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-CSRF-Token': csrfToken
  },
  body: JSON.stringify({ name: 'Alice' })
});

The server validates that the cookie value matches the header value. If they differ or the header is missing, the request is rejected.

Key Takeaway: The double submit cookie pattern defends against CSRF by requiring the frontend to read a cookie and echo its value in a custom header—something an attacker's cross-origin script cannot do.