What is CORS?
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that lets a server explicitly allow web pages from other origins to read its responses, using HTTP headers like Access-Control-Allow-Origin; without that permission, the browser blocks the page's JavaScript from reading the response.
Why it exists
The same-origin policy stops a page on a.com from reading data from b.com with the user's cookies. CORS is the controlled exception: the server at b.com says which origins may read its responses.
Simple vs preflighted requests
- Simple requests (
GET/HEAD/POSTwith basic headers and content types like form data): the browser sends the request with anOriginheader and checks the response'sAccess-Control-Allow-Origin. - Preflighted requests (other methods like
PUT/DELETE, custom headers such asAuthorization, orContent-Type: application/json): the browser first sends anOPTIONSrequest asking permission. The server must reply withAccess-Control-Allow-MethodsandAccess-Control-Allow-Headers(cacheable withAccess-Control-Max-Age).
Credentials
To send cookies cross-origin, the client uses credentials: "include", and the server must reply with Access-Control-Allow-Credentials: true and a specific origin, not *.
Key facts for interviews
- CORS is enforced by the browser. Servers,
curland Postman ignore it. - A CORS error means the request may still have reached the server; only reading the response was blocked. It is not a protection against CSRF.
- It is fixed on the server (or with a proxy on your own origin), never in client code.
Access-Control-Allow-Origin: *is fine for public data, never for authenticated APIs.
Code example
1// Server side (Node.js + Express): allow a specific front-end origin2import express from "express";34const app = express();5const ALLOWED = new Set(["https://app.example.com", "http://localhost:3000"]);67app.use((req, res, next) => {8 const origin = req.headers.origin;9 if (origin && ALLOWED.has(origin)) {10 res.setHeader("Access-Control-Allow-Origin", origin); // a specific origin, not "*"11 res.setHeader("Access-Control-Allow-Credentials", "true"); // allow cookies12 res.setHeader("Vary", "Origin"); // caches must key on Origin13 }14 if (req.method === "OPTIONS") {15 // preflight: answer which methods/headers are allowed, and cache it16 res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");17 res.setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization");18 res.setHeader("Access-Control-Max-Age", "600");19 return res.sendStatus(204);20 }21 next();22});2324app.get("/api/me", (req, res) => res.json({ name: "Ada" }));25app.listen(4000);2627// Client side (runs on https://app.example.com):28// await fetch("https://api.example.com/api/me", { credentials: "include" });
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.