π What is CORS?
π Definitionβ
CORS (Cross-Origin Resource Sharing) is a security mechanism that tells browsers to allow access to resources from different origins. Browsers restrict cross-origin resource requests by default for security reasons, and CORS is the method to safely permit this.
π― Understanding with Analogyβ
Apartment Security Systemβ
Imagine you live in Building A:
- Same-Origin: Call from A-101 to A office β Freely allowed β
- Cross-Origin: Call from A-101 to B office β Security check required π
- CORS Setting: Building B says "I'll accept calls from Building A" β Call allowed β
βοΈ How It Worksβ
1. What is Origin?β
Origin is the combination of protocol, domain, and port:
https://www.example.com:443/page
β β β β
β β β ββ Port (443 if omitted)
β β ββββββββββββββ Domain
β ββββββββββββββββββ Protocol
βββββββββββββββββββββββββ Origin
2. Same-Origin vs Cross-Originβ
// Current page: https://www.example.com
β
Same-Origin
- https://www.example.com/page
- https://www.example.com/api/users
β Cross-Origin
- http://www.example.com // Different protocol
- https://api.example.com // Different domain
- https://www.example.com:8080 // Different port
3. CORS Request Processβ
Simple Requestβ
1. Browser β Server: Send request
GET https://api.example.com/data
Origin: https://www.mysite.com
2. Server β Browser: Response
Access-Control-Allow-Origin: https://www.mysite.com
3. Browser: Check response
- If allowed origin β Deliver data β
- If not allowed β CORS error β
Preflight Requestβ
1. Browser β Server: Pre-check (OPTIONS)
OPTIONS https://api.example.com/data
Origin: https://www.mysite.com
2. Server β Browser: Permission response
Access-Control-Allow-Origin: https://www.mysite.com
Access-Control-Allow-Methods: POST, GET
3. Browser β Server: Actual request (POST)
4. Server β Browser: Data response
π‘ Real Examplesβ
Enabling CORS on Serverβ
Express.js (Node.js)β
const express = require('express');
const cors = require('cors');
const app = express();
// Method 1: Allow all origins (development)
app.use(cors());
// Method 2: Allow specific origin (production recommended)
app.use(cors({
origin: 'https://www.mysite.com',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
credentials: true,
maxAge: 3600
}));
// Method 3: Allow multiple origins
const allowedOrigins = [
'https://www.mysite.com',
'https://admin.mysite.com'
];
app.use(cors({
origin: function(origin, callback) {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
}
}));
π€ FAQβ
Q1. Why is CORS needed?
A: For security. Without CORS:
// Malicious site (evil.com)
fetch('https://bank.com/api/transfer', {
method: 'POST',
credentials: 'include', // Includes user's bank cookies
body: JSON.stringify({
to: 'hacker-account',
amount: 1000000
})
});
// CORS blocks such attacks!
Q2. How to solve CORS errors?
A: Depending on the situation:
// 1. If you control the server β Add CORS headers (recommended)
app.use(cors({ origin: 'https://frontend.com' }));
// 2. If you don't control server β Use proxy server
// package.json (Create React App)
{
"proxy": "https://api.example.com"
}
// 3. Development environment β Proxy middleware
// setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use('/api', createProxyMiddleware({
target: 'https://api.example.com',
changeOrigin: true
}));
};
Q3. When to use credentials: 'include'?
A: When sending cookies or authentication information:
// Frontend
fetch('https://api.example.com/profile', {
credentials: 'include' // Include cookies
});
// Backend - Must explicitly specify origin
app.use(cors({
origin: 'https://www.mysite.com', // Cannot use '*'!
credentials: true
}));
Q4. Difference between CORS and CSRF?
A: Completely different security concepts:
CORS (Cross-Origin Resource Sharing)
ββ Purpose: Allow cross-origin resource access
ββ Operation: Browser blocks/allows responses
ββ Solution: Add allow headers on server
CSRF (Cross-Site Request Forgery)
ββ Purpose: Prevent forged requests
ββ Operation: Malicious site sends requests
ββ Solution: Use CSRF tokens
π¬ Summaryβ
CORS is a core web security concept:
- Origin: Combination of protocol + domain + port
- Same-Origin Policy: Blocks different origins by default
- CORS: Safely allows different origins
- Preflight: Pre-check for complex requests
When CORS errors occur, don't panic - resolve safely by setting appropriate headers on the server! πβ¨