CORS (Cross-Origin Resource Sharing)
Is a security feature implemented by web browsers to control how web pages can request resources from a different domain (origin) than the one the page was served from.
🌍 What is an “Origin”?
An origin is defined by:
<protocol>://<hostname>:<port>
Examples:
https://example.com
≠http://example.com
(different protocol)https://api.example.com
≠https://example.com
(different subdomain)
🚫 Problem: Same-Origin Policy (SOP)
The Same-Origin Policy blocks web pages from making AJAX requests to a different origin for security reasons.
Example:
Your site athttps://myapp.com
tries to fetch data fromhttps://api.otherdomain.com
→ Blocked by browser unless CORS is enabled.
✅ Solution: CORS
CORS lets the server specify who is allowed to access its resources using special HTTP headers.
🔐 Common CORS Headers (Sent by Server)
Header | Purpose |
---|---|
Access-Control-Allow-Origin | Specifies allowed origins (e.g., * or https://example.com ) |
Access-Control-Allow-Methods | Lists allowed HTTP methods (GET, POST, etc.) |
Access-Control-Allow-Headers | Lists allowed custom headers (e.g., Authorization ) |
Access-Control-Allow-Credentials | Allows cookies/auth headers if set to true |
🧪 Simple Example (Server Response)
Access-Control-Allow-Origin: https://myapp.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Credentials: true
🔧 Enabling CORS (Examples)
Node.js (Express):
const cors = require('cors');
app.use(cors({ origin: 'https://myapp.com', credentials: true }));
PHP (header example):
header("Access-Control-Allow-Origin: https://myapp.com");
header("Access-Control-Allow-Methods: GET, POST");
⚠️ CORS Errors Are Client-Side Browser Rejections
CORS is enforced only by browsers, not by servers.
A failed CORS request won’t even reach your backend logic—it’s blocked by the browser.
🔥 Preflight Requests
For non-simple requests (e.g., using PUT
, DELETE
, or custom headers), the browser sends a preflight request using OPTIONS
method to check if the server allows the real request.
🛡️ Never Use Access-Control-Allow-Origin: *
with Credentials
It’s insecure to allow all origins (*
) while sending cookies or auth headers.