CSRF Tokens: Frontend Implementation
You'll learn how to properly include and manage CSRF tokens in your forms and AJAX requests to protect state-changing operations.
The Core Idea
A CSRF token is like a secret handshake between your frontend and backend. The server generates a unique token for each session or request, and the frontend must include this token when submitting forms or making AJAX calls that change data. Without the correct token, the server rejects the request—even if you're authenticated. This prevents malicious sites from tricking your browser into making unwanted requests on your behalf.
Including Tokens in Forms
For traditional HTML forms, embed the CSRF token as a hidden input field:
<form method="POST" action="/api/update-profile">
<input type="hidden" name="csrf_token" value="abc123xyz789">
<input type="text" name="username">
<button type="submit">Update</button>
</form>
The server typically renders this token into your page template, ensuring each form submission includes it.
Managing Tokens in AJAX Requests
For JavaScript-driven requests, retrieve the token from a meta tag or cookie, then include it in request headers:
<meta name="csrf-token" content="abc123xyz789">
const token = document.querySelector('meta[name="csrf-token"]').content;
fetch('/api/update-profile', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': token
},
body: JSON.stringify({ username: 'newname' })
});
Many frameworks automatically handle token refresh and injection, but always verify the token is present before state-changing operations.
Key Takeaway: Always include CSRF tokens in forms via hidden fields and in AJAX requests via custom headers—this simple frontend step blocks most CSRF attacks by proving the request originated from your legitimate application.