CORS
CORS (Cross-Origin Resource Sharing) is the browser rule that lets a page on origin A read a response from origin B only if B's headers allow it. It is a server opt-in, not a JavaScript flag you can bypass.
Detailed Explanation
An origin is scheme + host + port. https://app.example and https://api.example are different. A <script src> or an image can still send a GET (that is not CORS). What CORS blocks is reading the response from script, and certain "non-simple" requests that first send an OPTIONS preflight.
A simple request (GET/POST/HEAD, a small set of headers, a simple content type) goes to the server. The browser hides the body from JS unless the response has Access-Control-Allow-Origin matching the page (or * for non-credentialed requests).
Anything else — PUT, JSON Content-Type, custom headers — triggers a preflight: OPTIONS with Access-Control-Request-Method and Access-Control-Request-Headers. The server must answer with Allow-Origin, Allow-Methods, Allow-Headers, and optionally Max-Age. Then the real request runs.
Credentials (fetch(..., { credentials: "include" })) forbid Allow-Origin: *. The server must echo the specific origin and send Access-Control-Allow-Credentials: true.
Node fetch and server-to-server HTTP have no CORS. CORS is a browser security UI for users, not an auth mechanism. A malicious site cannot read your API; a malicious user with curl still can. You still need real auth.
What it costs you: local-dev pain (localhost:5173 vs localhost:3000) and misconfigured *. A wildcard plus cookies is rejected. A missing preflight handler looks like a network error in fetch (TypeError), not a status code you can read.
Reach for CORS headers on the API that the browser calls. Reach for a same-origin proxy in dev (vite proxy) to avoid CORS during development. Reach for cookies + CSRF tokens when you use credentialed cross-origin calls.
Code Examples
Browser: hidden if the API does not send CORS headers
// Browser: hidden if the API does not send CORS headers
try {
await fetch("https://api.example.com/me", { credentials: "include" });
} catch (err) {
console.log(err.name); // => TypeError (often CORS or network)
}Express-style response headers for a known SPA origin
// Express-style response headers for a known SPA origin
function cors(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "https://app.example");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
if (req.method === "OPTIONS") {
res.statusCode = 204;
res.end();
return;
}
next();
}Common Gotchas
Failed CORS hides the status from JS
you cannot `res.status` a blocked response. Debug in the Network panel.
CORS is not authentication
lock the API with tokens or cookies plus CSRF, not with `Allow-Origin` alone.
Same-site `localhost` ports are different origins
`5173` vs `3000` needs CORS or a proxy.