CORS: The Complete Handbook for Modern Web APIs

CORS: The Complete Handbook for Modern Web APIs#

Cross-Origin Resource Sharing, or CORS, is one of the most misunderstood parts of web development. Teams lose hours to it because the browser error messages feel vague, framework defaults vary wildly, and many blog posts reduce the topic to β€œjust add Access-Control-Allow-Origin: *”.

That advice is often wrong.

CORS is not an authentication system, not a CSRF defense, and not a server-to-server access control mechanism. It is a browser-enforced policy layer that decides whether frontend JavaScript running on one origin may read a response from another origin.

CORS vs Same-Origin Policy: They're Not the Same Thing

I’ve heard developers say “I need to add CORS to my API for security” more times than I can count. That’s backwards. CORS doesn’t make your API more secure. In fact, it makes it less restricted. The security feature is the Same-Origin Policy. CORS is the controlled exception.

Let me clear this up once and for all.

Same-Origin Policy (SOP)#

The Same-Origin Policy is a built-in browser security mechanism. It’s been around since the early days of the web. Here’s what it does:

What Is CORS and Why Is It Ruining Your API Calls?

You’ve built a React frontend. You’ve built a Node.js API. They work perfectly when you test them separately. You wire them together, make your first API call, and…

Access to fetch at 'http://localhost:3001/api/users' from origin 
'http://localhost:3000' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

Sound familiar? Every developer hits this wall. And most developers respond by Googling “how to fix CORS” and pasting app.use(cors()) without understanding what they just did.