š 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)
Ā