Frontend Patterns

Pattern

CSRF Protection

Implement anti-CSRF tokens or SameSite cookies to prevent cross-site request forgery attacks.

CSRF Protection

Problem

Attackers trick authenticated users into performing unwanted actions by embedding malicious requests in external sites. Users unknowingly transfer money, change passwords, or delete data simply by clicking a link or visiting a compromised page while logged in.

Solution

Require unguessable tokens in state-changing requests to verify they originated from your application. This prevents attackers from tricking users into executing unwanted actions through malicious links or forms.

Example

This example demonstrates how to include a CSRF token in API requests to verify the request originated from your application.

// Include CSRF token in request headers to prevent cross-site forgery
fetch('/api/transfer', {
  method: 'POST',
  headers: {
    // Extract CSRF token from meta tag and include in request
    'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content,
    'Content-Type': 'application/json'
  },
  // Server verifies token before processing state-changing request
  body: JSON.stringify({ amount: 100 })
});

Benefits

  • Prevents attackers from forging requests on behalf of authenticated users.
  • Protects against unauthorized actions like fund transfers or data deletion.
  • Works alongside SameSite cookies for defense-in-depth.
  • Required for secure applications handling sensitive operations.
  • Relatively simple to implement with established patterns.

Tradeoffs

  • Adds complexity to every state-changing request handling.
  • Token management requires server-side session or cryptographic verification.
  • Can break legitimate cross-origin requests if not configured properly.
  • May interfere with API usage from mobile apps or third-party clients.
  • SameSite cookies alone may not provide complete protection in all scenarios.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.