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

Custom Request Headers as CSRF Defense

Using custom headers that cross-origin requests cannot set as an additional CSRF protection layer.

Custom Request Headers as CSRF Defense

You'll learn how adding custom HTTP headers to your API requests can prevent CSRF attacks by exploiting browser security restrictions.

What Makes This Work

When a malicious site tries to forge a request to your application, it's limited by the Same-Origin Policy. While simple requests (like basic POST forms) can be sent cross-origin, browsers prevent third-party sites from setting custom headers on those requests.

This creates a powerful defense: if your API requires a specific custom header, and your frontend includes that header with every state-changing request, attackers can't replicate it from their evil site.

How It Protects You

Think of custom headers like a secret handshake between your frontend and backend. A malicious form on evil.com can submit data to your API, but it can't add the custom header. Without that header, your server rejects the request—even if the user has valid session cookies.

Common custom headers used for CSRF defense:

X-Requested-With: XMLHttpRequest
X-CSRF-Protection: 1
X-Custom-Token: your-app-identifier

The browser's CORS preflight mechanism ensures that cross-origin requests with custom headers must be explicitly allowed by your server. Since your API only allows requests from your own domain, the attacker is blocked.

Implementation Pattern

Your frontend adds the header to every authenticated request. Your backend checks for its presence:

  • Header present → Legitimate request from your frontend
  • Header missing → Potentially forged cross-origin request → Reject

This works best combined with other defenses (SameSite cookies, CSRF tokens), but can stand alone for single-page applications where all requests use fetch() or similar APIs that support custom headers.

Key Takeaway: Custom request headers exploit the Same-Origin Policy to prevent CSRF—attackers cannot set them from cross-origin contexts, making their absence a red flag for forged requests.