CORS vs CSRF — What is the Difference?
CORS and CSRF both involve cross-origin requests but they are completely different mechanisms. CORS is a browser policy that controls which origins can read API responses. CSRF is an attack where a malicious site tricks your browser into making requests using your existing session.
CORS — what it is
CORS controls whether JavaScript on one origin can read a response from another origin. If api.example.com does not include Access-Control-Allow-Origin for app.example.com, the browser blocks JavaScript from reading the response.
CORS does not prevent requests from being made — it prevents the response from being read by JavaScript on unauthorized origins.
CSRF — what it is
CSRF (Cross-Site Request Forgery) tricks a logged-in user's browser into making a request to a site where they have an active session — without their knowledge. The request includes their session cookie automatically.
<!-- Attacker's page — user is logged into bank.example.com --> <img src="https://bank.example.com/transfer?amount=1000&to=attacker"> <!-- Browser makes the request and includes the user's session cookie -->
Why CORS does not prevent CSRF
A CSRF attack using a simple GET (like the img src above) does not go through CORS — simple requests are not preflighted. Even with strict CORS, the request is still made and the session cookie is still sent. CORS only controls whether the response can be read by JavaScript, not whether the request is made.
What actually prevents CSRF
- SameSite cookie attribute —
Set-Cookie: session=abc; SameSite=Laxprevents cookies from being sent on cross-site requests - CSRF tokens — random tokens in forms that the server verifies
- Custom request headers — AJAX requests with custom headers trigger a CORS preflight, which blocks the request if the origin is not allowed
Summary
| CORS | CSRF | |
|---|---|---|
| What it is | Browser policy on cross-origin response access | Attack exploiting trusted session cookies |
| Who enforces it | Browser | Nothing automatically — you must implement protection |
| What it protects | Your API responses from unauthorized reads | Your server from unintended state changes |
| Fix | Correct CORS headers on your API | SameSite cookies, CSRF tokens |