How CORS works

· 2 min read

#how-it-works#web

CORS is how a server tells the browser that a page from another origin may read its responses. The idea to keep: the browser blocks that read by default, and the server's headers lift the block.

The short version

An origin is a scheme, a domain and a port. A page's script can read responses from its own origin, and from another origin only if the server sends CORS headers that allow it. The browser adds an Origin header to cross-origin requests, and the server answers with Access-Control-Allow-Origin.

The CORS preflight and the real request A page script on origin A calls fetch. The browser first sends an OPTIONS preflight to the server on origin B, and the server answers with allow headers. The browser then sends the real request, and the server answers with Access-Control-Allow-Origin. Simple requests skip the first two steps. Page script origin A Browser Server origin B fetch() 1 OPTIONS 2 Allow headers 3 real request 4 Allow-Origin Simple requests skip steps 1 and 2
Simplified: a preflighted request sends an OPTIONS request before the real one.

Step by step

  1. A script on origin A calls fetch() for a URL on origin B.
  2. A simple request (GET, HEAD or POST with a basic content type) goes out directly with an Origin header.
  3. Anything else, such as a PUT or a custom header, first gets an OPTIONS preflight with Access-Control-Request-Method and Access-Control-Request-Headers.
  4. The server answers with Access-Control-Allow-Origin, Access-Control-Allow-Methods and Access-Control-Allow-Headers.
  5. The browser sends the real request. Its response must carry Access-Control-Allow-Origin, or the script cannot read it.
  6. Access-Control-Max-Age tells the browser how long to cache the preflight answer.
Simple request Preflighted request
Typical case GET, HEAD, basic POST PUT, custom header
Sent first the request itself OPTIONS
Server must allow the origin origin, methods, headers

Why it matters

The browser decides whether your script may read a response, so a CORS error means the server did not send the right headers. The upside is that a server can open itself to chosen origins. The catch is cookies: with credentials the server must name the origin instead of * and send Access-Control-Allow-Credentials: true.

Sources