Learning on Web Dev Open is free for all.

Backend Engineering > Designing an API someone else has to useWhat CORS actually blocks
Phase 05Designing an API someone else has to use252 of 434

What CORS actually blocks

Not your server. Not the request, usually. A browser rule about who is allowed to read a response, and a preflight you should be able to explain.

Concept15 minAI adversary

CORS is enforced by the browser, on behalf of the user, against the page. Your server is not blocking anything; the browser made the request, got the response, saw no header permitting this origin to read it, and threw the result away before your JavaScript could see it. This is why curl works while the page does not, and why a CORS error is never fixed in the front end.

The preflight is a separate OPTIONS request the browser sends first when the real request is not simple: a method other than GET, HEAD or POST, a custom header such as Authorization, or a JSON content type. It asks whether the real request is allowed. If your API returns 404 for OPTIONS because you never registered a handler, every non-trivial request from a browser fails before it is sent, and the error message will point at the wrong thing.

The thing CORS does not do is protect your API. It stops a random page from reading responses with the user's cookies attached; it does not stop anyone with a terminal. Authentication and authorisation are still entirely your job, and a permissive CORS policy on a well-authorised API is a much smaller problem than a strict one on an open API.

You should now be able to

  • Explain who enforces CORS and who does not
  • Read a preflight exchange and say why it happened
  • Configure origins, credentials and headers without using a wildcard everywhere
Ask the community

Loading…