Cross-Origin Resource Sharing

A page loaded from one origin often needs data from another origin. For example, frontend code served from one domain may call an API on another domain.

Browsers do not give script free access to every cross-origin response. Cross-Origin Resource Sharing, or CORS, is the HTTP-header mechanism a server uses to say which origins may read selected responses in the browser.

The Boundary

An origin is defined by the scheme, host, and port. Changing any of those can make a request cross-origin.

CORS is easy to misunderstand because it is not a general server firewall. The server may still receive a request. The browser decides whether frontend JavaScript is allowed to read the response.

Simple Cross-Origin Reads

For some low-risk request shapes, the browser sends the actual request directly and includes an Origin header.

The server can expose the response by returning an Access-Control-Allow-Origin header. The value can be a specific origin, or * for non-credentialed responses that may be read by any origin.

If the response does not contain an acceptable CORS policy, browser script gets a CORS failure instead of the response body.

Preflight

Some cross-origin requests need a check before the real request is sent. This is called a preflight.

The browser sends an OPTIONS request that describes the intended method and headers:

Origin: https://app.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type, x-request-id

The server answers with the cross-origin policy it is willing to allow:

Access-Control-Allow-Origin: https://app.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: Content-Type, X-Request-ID
Access-Control-Max-Age: 86400

Only after the preflight succeeds does the browser send the actual request.

Credentials

Cross-origin credentials are stricter. By default, browser APIs such as fetch() do not send credentials on cross-origin requests.

If frontend code asks to include credentials, the server response must opt in with Access-Control-Allow-Credentials: true. The server also needs to name the allowed origin explicitly; wildcard origin access is not enough for credentialed responses.

Cookie behavior still depends on browser cookie policy. A correct CORS header does not force a browser to send or store third-party cookies.

Debugging Shape

CORS errors are intentionally sparse in JavaScript. The script often learns only that the request failed. The browser console usually contains the actionable reason.

When debugging, inspect both sides of the exchange:

Sources