CORS: Why the Browser Blocked Your Fetch

CORS: Why the Browser Blocked Your Fetch in JavaScript: You wrote a five-line . It works in Postman. It fails in the browser with a red console message about .

Concept Explanation

You wrote a five-line fetch. It works in Postman. It fails in the browser with a red console message about Access-Control-Allow-Origin. Nothing is wrong with your code.

Here is what actually happened. By default the browser enforces the Same-Origin Policy: JavaScript on shop.com may not read responses from api.other.com. That rule is what stops evil.com from quietly loading your webmail inbox and reading it. CORS is the controlled exception: the server announces which origins are allowed to read its replies.

Two things people get wrong about this:

  • CORS is enforced by the browser, not the server. The request usually reached the server and ran. The browser just refused to hand you the response.
  • CORS is not a server-side defense. It protects users from other sites, not your API from attackers. Anything with curl ignores it entirely.

An "origin" is scheme + host + port. http://site.com and https://site.com are different origins. So are ports 3000 and 5173, which is why local development trips over this constantly.


Syntax or Core Structure

The server's side of the conversation

// Express, hand-rolled so you can see the headers
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', 'https://shop.com');
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization');
  if (req.method === 'OPTIONS') return res.sendStatus(204);  // preflight
  next();
});

Or with the package

const cors = require('cors');
app.use(cors({
  origin: ['https://shop.com', 'https://admin.shop.com'],
  credentials: true            // required to send cookies
}));

Sending credentials from the client

await fetch('https://api.other.com/me', {
  credentials: 'include'   // cookies travel; server must echo the exact origin
});

Key Features

  • Preflight: for anything beyond a "simple" request (custom headers, PUT/DELETE, a JSON content type), the browser first sends an OPTIONS request and only proceeds if the answer allows it.
  • Simple requests skip preflight: GET and POST with basic form or text content types go straight through.
  • Access-Control-Max-Age caches the preflight answer so you are not paying two round trips per call.
  • Access-Control-Expose-Headers is needed before JS can read a custom response header such as X-Total-Count.

Real World Example

A React app on localhost:5173 calling an API on localhost:3000. Same machine, different port, therefore different origin, therefore blocked. Teams usually solve it one of two ways: allow the dev origin explicitly in the API's CORS config, or route calls through the dev server's proxy so the browser only ever sees one origin. The proxy approach is nicer because production, where both sit behind the same domain, then behaves the same as development.


Common Mistakes

  • origin: '*' together with credentials. The spec forbids it. With credentials: 'include' you must echo one specific origin.
  • Reflecting whatever Origin the request sent. That is the same as allowing everyone, and it is a real vulnerability when cookies are involved.
  • Forgetting to answer OPTIONS. Auth middleware that rejects the preflight with a 401 produces a CORS error that looks nothing like the actual cause.
  • Trying to fix CORS in the frontend. No fetch option, no header you set on the request, can grant permission the server did not give.
  • Expecting the status code to be visible. A blocked response gives you a network-level failure, not a readable 403.

Best Practices

  • Keep an explicit allowlist of origins, ideally read from environment config so staging and production differ without a code change.
  • Use a dev-server proxy locally so you develop against a single-origin setup.
  • Only enable credentials when you actually rely on cookies; bearer tokens do not need it.
  • Remember that authentication and authorization still have to be enforced server-side. CORS is not a lock.

Practice Exercises

  1. The Blocked Call: Serve a page on one port and an API on another, fetch across them, and read the exact console message. Then fix it with one response header.
  2. The Preflight Hunt: Add an Authorization header to that fetch and find the OPTIONS request in the Network tab. Note which request carries the interesting headers.
  3. The Wildcard Trap: Try Access-Control-Allow-Origin: * with credentials: 'include', read the error, and explain in one sentence why the spec bans the combination.