How Does CORS Work Under the Hood?

We first have to think about the reason why this is even necessary. Every single browser has a security mechanism called “Same origin policy.” This mechanism makes sure that a possible evil script can’t execute some random API call to a random domain.

What is considered same origin?

By definition, the protocol , the port , and the host have to be equal to be considered as the same origin. This makes it clear that you can call any route on your server with any query parameters, but you can't call to another subdomain since a subdomain is a different host.

So https://my-awesome-app.com can't access https://api.my-awesome-app.com because the host is different, but https://my-awesome-app.com/api/v1/... with any route is always available.

How can we deactivate the same-origin policy for our server/client?

We have to set some HTTP headers to tell the client that some resources are available to them. The relevant headers are:

Access-Control-Allow-Origin , which has to be set to the domain requesting the resource. From our example above, this could be set to Access-Control-Allow-Origin: https://my-awesome-app.com .

, which has to be set to the domain requesting the resource. From our example above, this could be set to . Some other Access-Control-* headers can restrict some resources or set some permission parameters to further increase the security of the server.

The browser makes sure that it has access to the server by sending a pre-flight HTTP OPTIONS request to the server and therefore asking for the headers. After finishing that request and when the server approves it by sending the needed headers, the browser will send the actual request.