securityAnswer last reviewed July 2026

People mix up CORS and CSRF all the time. What does each one actually do, and how do they apply to a JSON API?

Strong answers keep CORS as a browser policy and CSRF as an attack, and know which one protects a request, especially for token or cookie APIs.

What an AI-prepared candidate might say

So CORS, cross-origin resource sharing, controls which origins can make requests to your API from a browser. Browsers block cross-origin requests by default, and CORS headers let your server name the origins that are allowed. CSRF, cross-site request forgery, is an attack, where a malicious site tricks a user's browser into sending a request to your site using the session cookie the user already has. They kind of solve different problems. CORS governs which origins can read your responses, and CSRF is more about unwanted requests reusing the user's credentials. To prevent CSRF you use anti-CSRF tokens, the SameSite cookie attribute, origin checks, that sort of thing. For CORS you set the allowed origins carefully instead of pairing a wildcard with credentials. And on an API that uses token-based auth in a header instead of cookies, CSRF matters less, because the browser doesn't attach the token on its own. You want to configure both correctly.

Senior
Locked

What CORS actually relaxes and who enforces it, what CSRF really exploits, and why the two need completely different defenses.

Unlock the depth
Staff
Locked

The right posture for a JSON API depending on whether it authenticates with cookies or bearer tokens, and the misconfig that turns CORS itself into the hole.

Unlock the depth
Follow-up chain
People mix up CORS and CSRF all the time. What does each one actually do, and how do they apply to a JSON API? | NodeBook