CSRF Protection in SPAs
What you'll learn: How to handle CSRF tokens in single-page applications where client-side routing and API calls replace traditional form submissions.
The SPA Challenge
In traditional multi-page applications, each form submission triggers a page reload, making it straightforward to embed fresh CSRF tokens in each rendered page. Single-page applications break this model—after the initial page load, all navigation happens client-side, and state-changing operations occur through API calls without page refreshes.
This creates a token management challenge: how do you obtain, store, and refresh CSRF tokens when the backend only renders HTML once?
Core Strategies for SPAs
Initial Token Retrieval: Read the CSRF token from a meta tag during app initialization (as you learned in lesson 2910). Store it in your application state or a dedicated token manager.
Token Persistence: Keep the token in memory throughout the SPA lifecycle. Include it in every state-changing API request using custom headers (lesson 2914) or as part of the request payload.
Token Refresh: Since SPAs run for extended periods, tokens may expire. Implement a mechanism to fetch fresh tokens via a dedicated API endpoint when needed, or handle 403/401 responses that signal an invalid token.
Combining Defenses: Layer CSRF protections by using SameSite cookies (lesson 2913) alongside token-based verification. The cookie provides baseline protection, while tokens add explicit verification for API calls.
Example Flow: Your React/Vue/Angular app loads → reads token from <meta name="csrf-token"> → stores in state → includes token in every fetch() or axios POST/PUT/DELETE request via custom header → refreshes token if server responds with expiration error.
Key Takeaway: In SPAs, manage CSRF tokens as long-lived application state that's initialized on load, attached to every state-changing API request, and refreshed when necessary—combining token-based protection with SameSite cookies for defense-in-depth.