DEV Community

Luka Vidaković
Luka Vidaković

Posted on

CORS mechanism in short

tl;dr

To allow cross-domain requests:

  • server needs to respond with correct HTTP headers for original endpoints(+ handle OPTIONS request on the same endpoints for some types of request)
  • client app/website only needs to take care of setting CORS mode of request if required by the request library/API like it is with window.fetch (mode parameter)

Why do we need CORS mechanism

Browsers block cross-origin resource access for security reasons. HTTP requests carry authentication/authorization information with them — think cookies, which are stored per-domain and auto-included in the request.

What is it

Set of instructions that declare acceptable resource access from remote origin(s), a sort of whitelist mechanism. Instructions are sent to the browser using specific HTTP headers. Some resources(API endpoint, file...) that need to be accessed cross-domain from a browser, need additional HTTP headers to signal the browser it's safe to fetch.

When to use it

Usually it's when you serve your website or an app from one domain and have other supporting services you need to talk to on other port or domain — by default browser blocks many of such requests. Full list of affected request types is on MDN

Browser side

When doing a cross-domain request, browsers look for specific HTTP response headers to deduce if it's safe to return the response data to the source that initiated the request. Domain of origin and HTTP method used must be explicitly allowed through HTTP response headers for request not to be cancelled.
Some request types will cause 2 actual HTTP requests being issued by the browser, first being preflight request(OPTIONS) that serves as light pre-check for resource access. In both cases, browser will look out for CORS headers allowing the access.

Note: For issuing cross-domain requests from Javascript code, you may need to set the mode of the request to CORS type like with window.fetch

Server side

Server should respond with appropriate headers for every resource which should be available cross-domain from a browser. Beware that some browser requests will also expect appropriate response for a preflight request at identical resource location. Headers used:

  • Access-Control-Allow-Origin
  • Access-Control-Allow-Methods
  • Access-Control-Allow-Credentials
  • Access-Control-Allow-Headers
  • Access-Control-Expose-Headers
  • Access-Control-Max-Age

Full explanations on MDN

Top comments (0)