Reading CSRF Tokens from Meta Tags
You'll learn how to extract CSRF tokens embedded in HTML meta tags and include them in your fetch requests to protect against Cross-Site Request Forgery attacks.
When your server generates a page, it often embeds a unique CSRF token in the HTML <head> as a meta tag. Your frontend JavaScript needs to read this token and attach it to every state-changing request (POST, PUT, DELETE).
Why Meta Tags?
Think of meta tags as a secure delivery mechanism—the server bakes the token into the initial HTML response where only your legitimate JavaScript can access it. Attackers on external sites can't read these values due to the browser's same-origin policy.
The Basic Pattern
Your HTML might contain:
<meta name="csrf-token" content="abc123xyz789">
Your JavaScript reads it using the DOM:
const token = document.querySelector('meta[name="csrf-token"]').content;
Then include it in your fetch requests, typically as a header:
fetch('/api/update-profile', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': token
},
body: JSON.stringify({ name: 'Alice' })
});
Centralize Token Reading
Create a utility function to avoid repetition:
function getCsrfToken() {
const meta = document.querySelector('meta[name="csrf-token"]');
return meta ? meta.content : null;
}
Now every fetch can call getCsrfToken() to grab the current token value.
Key Takeaway: Reading CSRF tokens from meta tags provides a secure, same-origin way to access server-generated tokens that you must attach to state-changing requests, preventing attackers from forging actions on behalf of your users.