CORS Internals & Same-Origin Policy
CORS (Cross-Origin Resource Sharing) is a browser-enforced security protocol that restricts web applications from requesting resources from a different origin (Protocol + Domain + Port) unless the destination server explicitly permits it via HTTP headers.
Why it matters in interviews
Visual & Interactive Explanation
CORS Preflight (OPTIONS) Handshake Lifecycle
Sequence & Data Exchange Flow
User triggers fetch('https://api.com/user', { headers: { 'Auth': '...' } })
1. Browser intercepts & sends Preflight: OPTIONS https://api.com/user
Headers: Origin: http://localhost:3000, Access-Control-Request-Method: PUT
2. Server verifies origin & returns 204 No Content
Headers: Access-Control-Allow-Origin: http://localhost:3000, Access-Control-Allow-Methods: PUT
3. Preflight approved! Browser sends actual PUT request
4. Server returns JSON data payload
Code Examples & Implementation
// next.config.js
module.exports = {
async rewrites() {
return [
{
// Client requests /api/backend/users (same origin -> no CORS!)
source: '/api/backend/:path*',
// Next.js server proxies to remote API server (server-to-server has no browser CORS!)
destination: 'https://api.production-backend.com/:path*',
},
];
},
};Interview-Ready Answers
CORS is a browser security mechanism that blocks cross-origin fetch requests unless the server responds with `Access-Control-Allow-Origin`. React cannot fix CORS; the destination server must provide the correct headers.
Official Documentation & Specifications
Follow-up Questions & Deep Dives
Common Mistakes & Anti-Patterns
- Trying to 'fix CORS' in React frontend code by adding `mode: 'no-cors'` (which renders responses opaque and unreadable)
- Setting `Access-Control-Allow-Origin: *` when `Access-Control-Allow-Credentials: true` is enabled (rejected by browser)
- Forgetting `Access-Control-Max-Age`, doubling HTTP latency for every API call due to constant OPTIONS calls
Real-World Architectural Scenario
A frontend engineer sets `fetch(url, { mode: 'no-cors' })` to fix a CORS error. The error disappears, but `await res.json()` returns empty undefined data. Why?
Rate Your Readiness
Rate how comfortably you can explain this in an interview to update your global readiness gauge: