CORS (Cross-Origin Resource Sharing)

Difficulty: Beginner

Question

What is CORS, why does the browser enforce it, and how does a preflight request work?

Answer

CORS (Cross-Origin Resource Sharing) is a browser mechanism that lets a server explicitly allow web pages from other origins to read its responses. By default the Same-Origin Policy blocks JavaScript on https://app.example.in from reading a response from https://api.other.com; CORS response headers like Access-Control-Allow-Origin relax that rule for origins the server trusts. CORS is enforced by the browser, not the server, so it protects users, not your API.

What counts as an origin

An origin is the triple scheme + host + port. These are all different origins:

  • https://swiggy.in vs http://swiggy.in (scheme)
  • https://swiggy.in vs https://api.swiggy.in (host)
  • http://localhost:3000 vs http://localhost:5173 (port)

That last one is why a React app on Vite's port 5173 calling an Express API on 3000 hits CORS errors in development.

Simple requests vs preflight

A simple request (GET, HEAD or POST with only safe headers and a Content-Type of text/plain, application/x-www-form-urlencoded or multipart/form-data) is sent directly. The browser then checks the response's Access-Control-Allow-Origin and hides the response from JS if it does not match.

Anything else triggers a preflight: an OPTIONS request sent first, asking permission.

  • Origin: https://app.example.in
  • Access-Control-Request-Method: PUT
  • Access-Control-Request-Headers: content-type, authorization

The server must reply with matching Access-Control-Allow-Origin, Access-Control-Allow-Methods and Access-Control-Allow-Headers. Access-Control-Max-Age lets the browser cache that answer. Sending Content-Type: application/json or an Authorization header always causes a preflight.

Credentials and the wildcard trap

To send cookies cross-origin, the client sets credentials: 'include' and the server must return Access-Control-Allow-Credentials: true and a specific origin. The browser rejects Access-Control-Allow-Origin: * together with credentials.

The classic misconfiguration is reflecting whatever Origin arrives back into Access-Control-Allow-Origin while also allowing credentials. That lets any website read authenticated responses from your API. Always compare against an allowlist, and add Vary: Origin so caches and CDNs do not serve one origin's headers to another.

What CORS is not

  • Not a server-side security control: curl and Postman ignore it completely.
  • Not CSRF protection: simple cross-site form POSTs are still sent; CORS only decides whether JS may read the response.
  • Not fixed on the frontend: the fix for a CORS error is a server header or a dev proxy (like Vite's server.proxy), never a client-side flag.
CORS preflight for a JSON PUT. The browser asks permission with OPTIONS before sending the real request.
  1. Browser (app.example.in) → API server: OPTIONS /profile with Origin header
  2. API server → Browser (app.example.in): 204 with Allow-Origin, Allow-Methods
  3. Browser (app.example.in) → API server: PUT /profile with JSON body
  4. API server → Browser (app.example.in): 200 with Allow-Origin header

Code examples

Allowlist-based CORS in Express

import cors from 'cors';

const allowlist = new Set([
  'https://app.example.in',
  'http://localhost:5173', // dev only
]);

app.use(cors({
  origin(origin, cb) {
    // Allow same-origin / server-to-server calls with no Origin header
    if (!origin || allowlist.has(origin)) return cb(null, true);
    cb(null, false); // no CORS headers, browser blocks the read
  },
  credentials: true,                 // Access-Control-Allow-Credentials: true
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  maxAge: 600,                       // cache preflight for 10 minutes
}));

The `cors` package echoes the specific allowed origin and sets `Vary: Origin`, which is required when credentials are allowed.

Calling it from the browser with cookies

const res = await fetch('https://api.example.in/profile', {
  method: 'PUT',
  credentials: 'include', // send cookies cross-origin
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Asha' }),
});

The JSON content type plus a PUT method makes the browser send a preflight first.

Key points

  • Origin = scheme + host + port; any difference makes it cross-origin.
  • CORS is enforced by browsers; curl and server-to-server calls ignore it.
  • Non-simple requests (JSON body, Authorization header, PUT/DELETE) trigger an OPTIONS preflight.
  • Credentials cannot be combined with Access-Control-Allow-Origin: *.
  • Reflecting any Origin with credentials allowed is a serious misconfiguration.

Common follow-up questions

  • Why does Postman work when the browser shows a CORS error?
  • Why does a request with Content-Type application/json trigger a preflight?
  • Does CORS protect your API from attackers? What does it actually protect?
  • How would you fix CORS errors in local development without changing production config?

Interview tips

  • Start with the Same-Origin Policy; CORS only makes sense as a controlled relaxation of it.
  • Stress that CORS is a browser feature and not an API access control. Interviewers love this point.
  • Mention the wildcard plus credentials rule and origin reflection as real misconfigurations.

Concepts covered

Same-Origin Policy, CORS, Preflight Request, Access-Control-Allow-Origin, Credentials

More Web Security (OWASP, JWT, XSS, CSRF) questions