CORS

Also known as: Cross-origin resource sharing

On this page 8

CORS, or cross-origin resource sharing, is an HTTP-header-based mechanism that lets a server tell the browser which other origins may read its responses. Among browser technologies on the Web, it is the controlled exception to the same-origin policy, which by default stops a script on one origin from reading data returned by another.

CORS is defined in the WHATWG Fetch Standard and is enforced entirely by the browser. The server only declares its policy in response headers; the browser decides whether the calling page receives the response. This division of labor explains most of the confusion around CORS errors.

How CORS relaxes the same-origin policy

CORS works by adding an origin check on the response side. An origin is the combination of scheme, host and port, so app.example.com and api.example.com served over HTTPS are different origins, and so are http and https versions of the same host. When a script calls fetch() or XMLHttpRequest toward another origin, the browser attaches an Origin request header that names the calling page.

The server answers with Access-Control-Allow-Origin. If the value matches the calling origin or is the wildcard *, the browser hands the response to the script. If the header is missing or does not match, the request may still have reached the server, but the browser withholds the response body and reports a CORS error in the console. CORS therefore protects the reading of data, not the sending of requests.

The table below shows how the browser classifies typical request pairs before any CORS logic applies.

Page (scheme, host, port)Target (scheme, host, port)Classification
HTTPS, shop.example.com, 443HTTPS, shop.example.com, 443Same origin
HTTPS, shop.example.com, 443HTTPS, api.example.com, 443Cross origin (different host)
HTTP, shop.example.com, 80HTTPS, shop.example.com, 443Cross origin (different scheme)
HTTPS, shop.example.com, 443HTTPS, shop.example.com, 8443Cross origin (different port)
Same-origin and cross-origin request pairs

Simple requests and preflight requests

The Fetch Standard divides cross-origin requests into simple requests and requests that need a preflight. A simple request uses GET, HEAD or POST, carries only CORS-safelisted headers, and, for POST, uses one of three content types: text/plain, multipart/form-data or application/x-www-form-urlencoded. These requests are sent directly, because ordinary HTML forms could already send them before CORS existed.

Any other request triggers an OPTIONS preflight. The browser first asks the server, through Access-Control-Request-Method and Access-Control-Request-Headers, whether the real request is acceptable. Only if the server approves the method and headers does the browser send the actual request. A JSON body with Content-Type: application/json or a custom Authorization header is enough to require a preflight.

The following table summarizes the main CORS response headers and their roles.

HeaderPurposeTypical value
Access-Control-Allow-OriginNames the origin allowed to read the responseThe exact calling origin
Access-Control-Allow-MethodsLists methods approved in a preflightGET, POST, PUT, DELETE
Access-Control-Allow-HeadersLists request headers approved in a preflightContent-Type, Authorization
Access-Control-Allow-CredentialsPermits cookies and HTTP authenticationtrue
Access-Control-Expose-HeadersMakes extra response headers readable to scriptsX-Request-Id
Access-Control-Max-AgeCaches the preflight result in seconds600 to 7200
Core CORS response headers

Browsers cap the preflight cache duration regardless of the value sent: Chromium limits it to two hours, and Firefox to one day. Preflights add one extra round trip, so a sensible Access-Control-Max-Age noticeably reduces latency for chatty single-page applications.

Credentials and the wildcard restriction

By default, cross-origin fetch() calls do not send cookies. A script must opt in with credentials: "include", and the server must answer with Access-Control-Allow-Credentials: true. In that case the specification forbids the wildcard: Access-Control-Allow-Origin must name the exact origin, and the allowed methods and headers must also be listed explicitly.

This restriction exists because a wildcard combined with cookies would let any website read authenticated data on behalf of a logged-in user. Servers that support several trusted front ends usually keep an allowlist of origins and echo the matching one back. When they do, they must add Vary: Origin so that shared caches and the browser cache do not serve a response tailored to one origin to another.

CORS is often confused with neighboring security mechanisms, but each answers a different question. The comparison below separates them.

MechanismQuestion it answersWho sets it
Same-origin policyMay a script read another origin by defaultBrowser, built in
CORSWhich other origins may read this responseServer, via headers
Content Security PolicyWhich sources may this page load or contactPage owner, via header
CSRF tokensDid this state-changing request come from my siteApplication logic
Cross-Origin Resource PolicyMay other origins embed this resource at allServer, via header
CORS and related browser security mechanisms

The most important distinction is with CSRF protection. Because simple requests are delivered before any CORS check, CORS does not prevent cross-site request forgery. An attacker page can still submit a form-encoded POST to a vulnerable endpoint; it simply cannot read the answer. State-changing endpoints therefore still need SameSite cookies, anti-CSRF tokens or both.

Configuring CORS on a server

Good CORS configuration starts from the principle of least privilege: allow only the origins, methods and headers that real clients need. The decision table below covers the most common situations.

SituationRecommended settingReason
Public, read-only open data APIWildcard origin, no credentialsData is not user specific
Own front end on a separate subdomainExact origin, credentials allowedSession cookies must flow
Several partner front endsOrigin allowlist with Vary: OriginEach response names one origin
Internal service called only by serversNo CORS headers at allBrowsers never call it
Local development on localhostSeparate development allowlistKeeps production policy strict
Choosing a CORS configuration

The preflight must be answered before authentication, because browsers never attach credentials to the OPTIONS request. A frequent production bug is an authentication layer that rejects the preflight with 401 or 403, which the browser reports as a generic CORS failure even though the headers are configured correctly elsewhere.

Common CORS mistakes and misconceptions

Most CORS problems come from a small set of recurring misunderstandings. The table links each symptom to its usual cause.

SymptomLikely causeFix
No Access-Control-Allow-Origin headerServer or proxy omits the headerAdd the header at the right layer
Wildcard rejected with credentialsUsing * together with cookiesEcho the exact allowed origin
Preflight fails with 401Authentication runs on OPTIONSExempt preflight from authentication
Custom header unreadable in scriptHeader not exposedList it in Access-Control-Expose-Headers
Random failures behind a CDNMissing Vary: OriginAdd Vary: Origin to responses
Typical CORS errors and fixes
  • Reflecting any Origin value with credentials enabled is equivalent to having no protection and is a well-known security vulnerability.
  • Allowing the null origin is risky, because sandboxed iframes and local files can produce it.
  • Disabling CORS in the browser or with an extension only hides the problem on one machine; real users still see the error.
  • CORS does not apply to server-to-server calls or tools such as curl, which ignore browser policy entirely.

The idea in brief

A web page is normally allowed to read data only from the website it came from. This rule, the same-origin policy, keeps a random site from quietly reading your email or bank account in another tab.

CORS is the polite permission note a server can send back. It says, in effect, that a named website may read this reply. The browser acts as the gatekeeper: it checks the note and either passes the data to the page or blocks it. The key point is that the server grants permission and the browser enforces it.

A practical scenario

A retail company moves its storefront to the shop.example.com host while its product API stays on api.example.com. After deployment, the cart stops working and the console shows a CORS error on every POST that sends JSON with a session cookie.

The backend team finds two faults. The API returns Access-Control-Allow-Origin: *, which browsers reject when credentials are included, and an authentication middleware answers the OPTIONS preflight with 401. They replace the wildcard with an allowlist echoing the storefront origin, add Access-Control-Allow-Credentials: true and Vary: Origin, exempt preflights from authentication, and set Access-Control-Max-Age to 3600 seconds.

The cart works again within the same release, and because preflights are now cached, the number of OPTIONS requests drops sharply, cutting one round trip from most repeat API calls during a shopping session.