Security
CSRF in JavaScript Web Apps: How to Prevent It
CSRF tricks authenticated users into submitting requests to your server. If your API relies solely on cookies, a malicious website can make requests using the victim's session.
❌ Attacker's Forged Form
// Attacker's page sends a hidden form:
<form action='https://yourapp.com/api/transfer' method='POST' id='f'>
<input name='amount' value='10000'>
<input name='to' value='attacker_account'>
</form>
<script>document.getElementById('f').submit();</script>✅ Protected with CSRF Token
// Server: generate token
app.get('/api/csrf-token', (req, res) => {
res.json({ csrfToken: generateToken(req, res) });
});
// Client: include in mutating requests
const { csrfToken } = await fetch('/api/csrf-token').then(r => r.json());
await fetch('/api/transfer', {
method: 'POST',
headers: { 'x-csrf-token': csrfToken },
body: JSON.stringify({ amount: 100 })
});💡
Pro tip: Set SameSite=Strict on session cookies as an additional defense. Modern browsers won't send them with cross-site requests.
Paste this code into LearnCodeGuide
Detect JavaScript vulnerabilities and bugs automatically with AI-powered analysis.
Analyze JavaScript Code →