đ CORS (Cross-Origin Resource Sharing) â Explained Simply
đĄïž What is CORS?
CORS is a browser security feature that controls how a website running on one origin (domain) can make requests to another origin.
It’s designed to prevent malicious websites from reading sensitive data from other websites youâre logged into.
đ§ What is an “Origin”?
An origin = protocol + domain + port
Examples:
https://example.com
âhttp://example.com
(different protocol)https://example.com
âhttps://api.example.com
(different subdomain)https://example.com:443
=https://example.com
(same port)
â The Problem: Same-Origin Policy (SOP)
By default, the browser blocks JavaScript from making requests to a different origin.
Example:
Your sitehttps://yourapp.com
tries to get data fromhttps://api.otherdomain.com
â the browser blocks it.
â The Solution: CORS
CORS allows servers to tell browsers:
âYes, itâs safe to let this other origin access my resources.â
This is done using special HTTP headers in the serverâs response.
đ§ How CORS Works (Step-by-Step)
Your browser sends a request to a different origin.
The server checks if it allows that origin.
If allowed, it includes headers like:
httpAccess-Control-Allow-Origin: https://yourapp.com
Browser sees this and lets the response through.
đŠ Common CORS Headers
Header | Purpose |
---|---|
Access-Control-Allow-Origin | Whoâs allowed to access (e.g., * , https://example.com ) |
Access-Control-Allow-Methods | What HTTP methods are allowed (GET , POST , etc.) |
Access-Control-Allow-Headers | Which request headers are allowed (Content-Type , Authorization ) |
Access-Control-Allow-Credentials | Allow cookies or auth headers if true |
đ Preflight Requests (OPTIONS)
For non-simple requests (like PUT
, DELETE
, or custom headers), the browser sends a preflight request:
Method:
OPTIONS
Purpose: “Is it safe to send the real request?”
The server must respond with CORS headers even to this OPTIONS request.
đ§Ș Example: CORS in Action
Browser request to another origin:
fetch("https://api.example.com/data", {
method: "GET",
credentials: "include"
});
Server response:
Access-Control-Allow-Origin: https://yourapp.com
Access-Control-Allow-Credentials: true
â ïž Important Notes
CORS is enforced only by browsers (not cURL, Postman, etc.)
You cannot bypass CORS on the frontendâit must be handled by the server
Never use
Access-Control-Allow-Origin: *
withcredentials: true
đ ïž Want a Practical Example?
Let me know:
Your frontend language (e.g., HTML/JS, React)
Your backend (e.g., Node.js, PHP, Python)
Â