Left ArrowBack

notes / web dev / web / security / CORS

CORS

A CORS error message.

CORS

Planted

Status: seed

For security purposes, the browser implements the same-origin policy. A website can request data from its own URL. However, data from a different origin is blocked by the browser. CORS (Cross Origin Resource Sharing) is a mechanism that can remove this block.

A website address

Origin

A website's origin is its scheme + domain + port. When comparing 2 websites, if any of these is different, they have a different origin.

Request: Same Origin

When a website makes a GET request, the browser will add an origin property to the request headers. Its value will be the website's origin. The server will add an Access-Control-Allow-Origin property to the response headers. Its value will be the origin of the resource being requested. If both values match, the response data will be allowed by the browser.

Step-by-step how a website requests an asset from a server

Request: Different Origin

If the Origin & Access-Control-Allow-Origin values don't match, the browser will block the response data.

Step-by-step how a CORS error occurs

Request: Allow Cross-Origin

To allow cross-origin requests, middleware can be used on the server to adds specific origins to the response header. This is called whitelisting an origin.

Step-by-step how a CORS error can be solved

Access-Control-Allow-Origin can be set to *. This value is a wildcard. It allows any URL to make requests.

Preflight

Some HTTP requests have non-standard headers. For example; PUT, PATCH & DELETE. These requests need to be preflighted:

  1. 1. Before making the primary request, the browser make a different request (a preflight request) using the options HTTP verb.
  2. 2. The server inspects the origin & request method. It then responds, stating if the primary request is allowed.
  3. 3. If allowed, the browser makes the primary request.

If you server doesn't allow the request, look for the Access-Control_Allow-Origin header in the response. If there is none, you may need to enable CORS on the server.

Note, preflight requests no longer show in the browser's network tab.

Tachometer

Performance

Preflighting means that every request the client is making could actually be 2. On the server, this can be reduced by adding an Access-Control-Max-Age: 84600 header. This will cache a preflight for a specified time. Nick Olinger details another performance approach he used while working at meetup.com By keeping a website & API on the same origin, you remove the need for perflighting.

Where to Next?

A sci-fi robot taxi driver with no lower body