CORS is one of those things developers "fix" before they understand.
An error shows up. Requests fail. Someone adds a header.
It works. But the reason it exists is usually misunderstood.
First, what CORS actually is
CORS stands for Cross-Origin Resource Sharing.
It's a browser security mechanism that controls:
- which origins can access a server's resources
- using explicit permission from the server
Important detail:
- CORS is enforced by the browser
- not by the server
- not by your API
The server only declares rules. The browser enforces them.
Why CORS exists at all
Without CORS, any website could:
- read data from another site
- act on a user's behalf
- steal sensitive information
Imagine visiting a random website and it silently reading your bank data.
CORS exists to prevent that.
It builds on the same-origin policy, which blocks cross-origin access by default.
How CORS works in simple terms
When a browser makes a cross-origin request, it:
- checks response headers
- looks for permission like
Access-Control-Allow-Origin
If permission exists, the response is usable. If not, the browser blocks it.
The request still reaches the server. The browser just refuses to expose the response.
What about preflight requests?
For certain requests, the browser sends an OPTIONS request first.
This is the preflight.
It asks:
- which methods are allowed
- which headers are permitted
- whether credentials are supported
Only after approval does the real request happen.
The most common misconception
CORS does not protect your backend.
It protects users in the browser.
That's why:
- Postman ignores CORS
- server-to-server requests ignore CORS
Understanding this clears up a lot of confusion.
CORS is not a bug. It's a safety belt.
It feels annoying because it blocks things early. But without it, the web would be fundamentally unsafe.