Course contentsShow
← Security
Lesson 872 of 3,05218. Web Security - CSRF and Request ForgeryFree lesson

CSRF Protection for AJAX and SPAs

Implement CSRF defenses in single-page applications using custom headers and token handling.

CSRF Protection for AJAX and SPAs

What you'll learn: How to implement CSRF defenses specifically for single-page applications (SPAs) and AJAX-heavy interfaces using custom headers and token management strategies.

The Challenge in Modern Applications

Single-page applications and AJAX requests work differently from traditional form submissions. They make background HTTP requests via JavaScript, which means you can't rely solely on hidden form fields to pass CSRF tokens. However, this JavaScript-driven architecture actually provides unique security opportunities.

Custom Headers: Your SPA's Best Friend

The most effective CSRF defense for AJAX is adding custom request headers. Simple requests (like form submissions) cannot add custom headers, but JavaScript can. Since CSRF attacks rely on the browser automatically sending credentials with cross-origin requests, and browsers won't automatically add custom headers for attackers, this creates a strong defense layer.

// Client-side: Add token via custom header
fetch('/api/transfer', {
  method: 'POST',
  headers: {
    'X-CSRF-Token': csrfToken,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ amount: 100 })
});
// Server-side: Validate the custom header exists and matches
if (request.headers['x-csrf-token'] !== session.csrfToken) {
  return response.status(403).json({ error: 'Invalid CSRF token' });
}

Token Delivery Strategies

Your SPA needs the token first. Common approaches:

  • Embed it in the initial HTML page load
  • Provide a dedicated /csrf-token endpoint
  • Include it in your authentication response
  • Store in a cookie readable by JavaScript (then send via header)

The key advantage: JavaScript running on your domain can read and attach tokens, while malicious cross-origin scripts cannot.

Key Takeaway: SPAs should implement CSRF protection using custom request headers containing tokens, leveraging the fact that attackers cannot force browsers to add custom headers in cross-origin requests—making this defense both elegant and effective.