-- views

What is Cross-Origin Resource Sharing?

March 17, 2024

Have you ever tried getting data from another website or a third-party service for your webpage? If so, you might have run into CORS errors that stop your webpage from getting the data it needs.

Web browsers have a security feature called CORS, which prevents web pages from making requests to domains, protocols, or ports different from the one that served the page (different origin).

An example of a cross-origin request: the front-end JavaScript code served from uses fetch() to make a request for


Origin is defined by the scheme (protocol), hostname (domain), and port of the URL used to access it.


The following are same origin because they have the same scheme (http) and hostname (


Same for these because a server delivers HTTP content through port 80 by default:


These are not the same origin because they use:

  • Different schemes:

  • Different hostnames:


For security purposes, browsers prevent cross-origin HTTP

What requests use CORS?#

CORS is enabled for the following requests:

  • fetch() or XMLHttpRequest request.
  • cross-domain font usage in @font-face within CSS and more.

Preflighted requests#

A preflight request is a CORS request that checks to see if the CORS protocol is understood and the server is aware of using specific methods and headers. it uses OPTION method, with some HTTP request headers:

  • Access-Control-Request-Method
  • Access-Control-Request-Headers
  • Origin

You can find further details regarding request headers in my blog post understanding-http-headers.

A preflight request is automatically used by the browser.

The server must respond to the preflight request with information about the cross-origin requests. The server response headers must include the following:

  • Access-Control-Allow-Methods

    Access-Control-Allow-Methods: GET, POST
  • Access-Control-Allow-Headers

    Access-Control-Request-Headers: Content-Type, x-requested-with
  • Access-Control-Allow-Origin


Share credentials with CORS#

If you want to send cookies or HTTP authorization when using CORS, which can identify the sender, you need to add additional headers to the request and response.

Add credentials: 'include' to the fetch options as in the following example to include the cookie with the request:

fetch('', {
  credentials: 'include'

The server must be set to a specific origin and Access-Control-Allow-Credentials must be set to true.

HTTP/1.1 200 OK
Access-Control-Allow-Credentials: true



Let’s work together

I build exceptional and accessible digital experiences for the web