CORS Explained

Cross-Origin Resource Sharing (CORS) is a security feature that lets a server tell the browser which websites (origins) can access its resources.

Same origin

When a browser makes a request, it includes an Origin header. If the request goes to a server with the same origin, the browser allows it and processes the response.

CORS same origin.

Different origin

If the request goes to a different URL, it’s considered a cross-origin request.

In response, the server will add an Access-Control-Allow-Origin header. The value of this header must match the Origin header from the request.

CORS different origin.

The server can also allow any URL to make a request by using a wildcard *.

CORS wild card origin.

Mismatch origin

If there’s a mismatch, the browser will block the response data from being shared with the client. This results in an error, but for security reasons, the browser doesn’t provide much information about what went wrong.

CORS mismatch origin.

You can fix the mismatch by configuring the server to respond with the correct CORS headers.

This is done by adding an Access-Control-Allow-Origin header to the server’s response, specifying which domains can access the resources.

Preflight requests

For some cross-origin requests, the browser first sends a preflight request to check if the server allows them.

This is the OPTIONS request you sometimes see in network tab before seeing the actual request.

It happens when:

The server responds with CORS headers Access-Control-Allow-Methods and Access-Control-Allow-Headers, to say which methods and headers are allowed.

If the response allows the request, the browser proceeds with sending it.

If not, the request is blocked, and a CORS error appears in the console.


Find this post helpful? Subscribe and get notified when I post something new!