CORS Deep Dive
Understand Cross-Origin Resource Sharing: preflight requests, headers, and credential handling.
What you'll learn
- Same-Origin Policy and why CORS exists
- Simple requests vs preflight requests
- CORS headers: Origin, Access-Control-Allow-Origin
- Credentialled requests and wildcard restrictions
Concept
CORS Deep Dive
Cross-Origin Resource Sharing (CORS) allows a web page to request resources from a different origin, bypassing Same-Origin Policy.
Same-Origin Policy
SOP prevents scripts on one origin from reading responses from another. An origin is scheme+host+port. CORS allows specific cross-origin requests.
Simple vs Preflight
Simple requests (GET/HEAD/POST with safe headers) are sent directly. Preflight requests (PUT/DELETE, custom headers) send OPTIONS first, then the actual request.
CORS Headers
Access-Control-Allow-Origin: which origins can read response. Allow-Methods: allowed methods. Allow-Headers: allowed headers. Max-Age: preflight cache duration. Server sets, browser enforces.
Credentials
By default, CORS doesn't send cookies. For credentials: fetch(url, {credentials:'include'}) and Allow-Credentials:true. With credentials, Allow-Origin cannot be * - must be specific origin.
Example
function corsMW(req, res, next) {
const origins = ['https://app1.example.com', 'https://app2.example.com'];
if (origins.includes(req.headers.origin)) {
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization');
res.setHeader('Access-Control-Max-Age', '86400');
}
if (req.method === 'OPTIONS') return res.status(204).end();
next();
}
const req = {headers:{origin:'https://app1.example.com'}, method:'OPTIONS'};
const res = {headers:{}, setHeader(k,v){this.headers[k]=v;}, status(c){console.log('Status:',c);return this;}, end(){console.log('Headers:',res.headers);}};
corsMW(req, res, () => console.log('Not preflight'));
The middleware sets CORS headers for allowed origins. OPTIONS preflight returns 204 with headers. Credentialled requests need specific origin (not *).
Try it
- JSON Formatter
CORS preflight responses are JSON-configured - format headers for debugging.
Common mistakes
The mistake
Setting Allow-Origin: * with credentials.
The fix
When Allow-Credentials is true, origin must be specific, not *. Echo the Origin header.
The mistake
Not handling OPTIONS preflight requests.
The fix
Server must respond to OPTIONS with 204 and CORS headers. Otherwise preflight fails.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.