CORS: what it is and how preflight works

Difficulty: Beginner

Question

What is CORS, why does it exist, and how does a preflight request work?

Answer

Start with the reason. Browsers enforce the same-origin policy: a script running on https://shop.example.com cannot freely read responses from https://api.other.com. Otherwise any website you visit could use your logged in session to fetch your bank data in the background. An origin is the combination of scheme, host and port. CORS, Cross-Origin Resource Sharing, is the controlled relaxation of that rule: the server tells the browser which foreign origins may read its responses. Important framing: CORS is enforced by browsers, not servers. curl, Postman and other servers ignore it completely, so it is not an authentication mechanism.

Simple requests are GET, HEAD or POST with a limited set of headers and content types such as form encoded or text/plain. The browser sends them directly with an Origin header, and if the response contains Access-Control-Allow-Origin matching the origin (or *), the script can read it. Note the request was still sent and possibly processed; CORS blocks reading the response, not sending, which is why CSRF protection is separate.

Anything else triggers a preflight. If the request uses methods like PUT, PATCH or DELETE, custom headers such as Authorization, or Content-Type application/json, the browser first sends an OPTIONS request with Origin, Access-Control-Request-Method and Access-Control-Request-Headers. The server answers with Access-Control-Allow-Origin, Access-Control-Allow-Methods and Access-Control-Allow-Headers, and optionally Access-Control-Max-Age to let the browser cache the preflight result and skip repeat OPTIONS calls. Only if the preflight passes does the browser send the real request.

Credentials: to send cookies or HTTP auth cross-origin, the client must set credentials: 'include' (fetch) and the server must respond with Access-Control-Allow-Credentials: true. In that case the wildcard is forbidden: Access-Control-Allow-Origin must name the exact origin, and so must the allowed headers and methods lists. Also set Vary: Origin when you echo origins dynamically, so caches do not serve one origin's headers to another.

Common mistakes. Reflecting any Origin header back with credentials enabled is equivalent to disabling the protection entirely. Using a naive substring or regex check, such as endsWith('example.com'), allows evilexample.com. Instead use an explicit allowlist. Forgetting to handle OPTIONS in the auth middleware, so preflight returns 401 and the browser reports a confusing CORS error, is another classic. Errors on a 500 response can also show up as CORS failures if the error path lacks the headers, so make sure error responses carry CORS headers too.

Debugging tip: the browser console message is the same for many causes, so inspect the network tab for the OPTIONS request and its response headers first.

Alternatives to CORS: put frontend and API behind the same origin using a reverse proxy, in which case no CORS is needed. JSONP is obsolete. For public read-only APIs, Allow-Origin * without credentials is fine.

Summary: same-origin policy protects users; CORS is the server's opt-in for exceptions; preflight is the browser asking permission before risky requests.

Code examples

Preflight exchange

OPTIONS /v1/orders HTTP/1.1
Origin: https://app.example.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: authorization, content-type

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 600
Vary: Origin

The browser caches this approval for ten minutes and then sends the real POST.

Express CORS with an allowlist

import cors from 'cors';
const ALLOWED = new Set(['https://app.example.com', 'https://admin.example.com']);
app.use(cors({
  origin: (origin, cb) => cb(null, !origin || ALLOWED.has(origin)),
  credentials: true,
  methods: ['GET','POST','PUT','PATCH','DELETE'],
  allowedHeaders: ['Authorization','Content-Type'],
  maxAge: 600
}));

Exact-match allowlist; place it before authentication so OPTIONS preflights never hit auth.

Key points

Common follow-up questions

Interview tips

Concepts covered

CORS, same-origin policy, preflight, credentials

More API Design questions