Back to cheatsheets
Developer
CSRF Prevention
Prevent Cross-Site Request Forgery with token-based protection, SameSite cookies, and Origin checks.
What you'll learn
- CSRF token (double-submit cookie)
- Origin / Referer validation
How to use these snippets
- Click the Copy button next to any snippet to copy it to your clipboard.
- Paste the code into your project, IDE, or terminal.
- Replace placeholder values (like
example.comoryour-secret) with your actual data. - Review the code comments for important security notes and caveats.
Code Snippets
Copy-paste code snippets
2 ready-to-use snippets for csrf prevention. Click copy and paste into your project.
CSRF token (double-submit cookie)
// Generate CSRF token
function generateCSRFToken() {
return crypto.randomUUID();
}
// Set as cookie (not HttpOnly — JS needs to read it)
res.cookie('csrf-token', token, {
secure: true,
sameSite: 'strict',
path: '/',
});
// Client sends token in header
fetch('/api/action', {
method: 'POST',
headers: {
'X-CSRF-Token': getCookie('csrf-token'),
},
body: JSON.stringify(data),
});
// Server compares cookie token vs header token
Origin / Referer validation
function validateOrigin(req) {
const origin = req.headers.origin;
const referer = req.headers.referer;
const allowed = ['https://example.com'];
if (origin && !allowed.includes(origin))
return false;
if (!origin && referer) {
const refOrigin = new URL(referer).origin;
if (!allowed.includes(refOrigin))
return false;
}
// Reject if neither present
if (!origin && !referer)
return false;
return true;
}
100% Free · No signup · No cost
Generate something unguessable right now
148 bits of entropy, a crack-time estimate you can trust, and a clipboard that clears itself after 30 seconds.
Part of the Toolly ecosystem · secure.toolly.site