What is CSRF and how do you prevent it?
By FrontendPro Editorial Team Updated 9/26/2026
Answer
CSRF tricks a logged-in user's browser into sending a request the user never intended. It works because browsers attach cookies to a request automatically based on its destination, regardless of which site triggered it.
A user is signed in to their bank, then visits a malicious page containing:
<form action="https://bank.example/transfer" method="POST" id="f">
<input name="to" value="attacker">
<input name="amount" value="5000">
</form>
<script>document.getElementById("f").submit();</script>
The browser sends the bank's session cookie with it, and the server sees a perfectly authenticated request. Note the attacker never reads the response — they only need the side effect.
Defences, strongest first
SameSitecookies.SameSite=Lax(the modern browser default) stops cookies being sent on cross-site POSTs, which kills the example above.Strictis tighter but logs users out when they arrive via an external link. This is your baseline, not your only layer.- Anti-CSRF tokens. The server puts an unpredictable token in the form or page, and rejects any state-changing request that does not echo it back. The attacker's page cannot read the token because the same-origin policy blocks it.
- Check
Origin/Refereron state-changing requests and reject mismatches. - Never use GET for anything that changes state. A
<img src="/delete?id=3">is enough to trigger it otherwise.
Two common misunderstandings
CORS does not protect you: it governs whether JavaScript may read a cross-origin response, while the form POST above is sent and processed regardless.
And storing the token in a cookie alone is not enough — unless you use the double-submit pattern, where the request must carry the same value in both a cookie and a header or body field.
