Table of Contents
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'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.
Request: Different Origin
Access-Control-Allow-Origin values don't match, the browser will block the response data.
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.
Access-Control-Allow-Origin can be set to
This value is a wildcard.
It allows any URL to make requests.
Some HTTP requests have non-standard headers.
These requests need to be preflighted:
- 1. Before making the primary request, the browser make a different request (a preflight request) using the options HTTP verb.
- 2. The server inspects the origin & request method. It then responds, stating if the primary request is allowed.
- 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.
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.