Skip to content
GeeksSmith
intermediate 6 min read

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

CORS is universally misunderstood by junior developers who assume it is a React or client bug. Interviewers use CORS questions to verify your understanding of browser security boundaries and HTTP network handshakes.

Visual & Interactive Explanation

CORS Preflight (OPTIONS) Handshake Lifecycle

Sequence & Data Exchange Flow

Browser
Next.js App
API Server
#1
BrowserNext.js App
request

User triggers fetch('https://api.com/user', { headers: { 'Auth': '...' } })

#2
BrowserAPI Server
request

1. Browser intercepts & sends Preflight: OPTIONS https://api.com/user

Headers: Origin: http://localhost:3000, Access-Control-Request-Method: PUT

#3
API ServerBrowser
response

2. Server verifies origin & returns 204 No Content

Headers: Access-Control-Allow-Origin: http://localhost:3000, Access-Control-Allow-Methods: PUT

#4
BrowserAPI Server
request

3. Preflight approved! Browser sends actual PUT request

#5
API ServerBrowser
response

4. Server returns JSON data payload

Code Examples & Implementation

Bypassing Local Dev CORS using Next.js Rewrites
// 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:

Rate your confidence: