HTTP, TLS & Web Performance

CORS Explained Without Tears

Understand why browsers block cross-origin requests, how preflights work and which response headers actually fix the error.

Key takeaways

  • An origin is the combination of scheme, hostname and port, and any difference makes a request cross-origin.
  • The same-origin policy stops scripts from reading other origins' data, and CORS is the controlled exception.
  • Some requests trigger a preflight, an OPTIONS request the server must approve before the real one is sent.
  • Requests with cookies need an exact allowed origin plus Access-Control-Allow-Credentials: true.
  • CORS protects browser users and is no substitute for authentication, because other clients ignore it.

CORS, short for Cross-Origin Resource Sharing, is the system a server uses to tell browsers, "pages from this other site may read my responses". Without that permission, a script on one origin can often send a request to another, but the browser will not hand it the answer.

So when your console shows a CORS error, the fix is almost always on the server that receives the request. It needs to return the right Access-Control- headers. Changing the front-end code alone rarely helps.

Origins and the same-origin policy

An origin is three things taken together: the scheme, the host and the port. Compare these against https://www.example.com:

Address Same origin? Why
https://www.example.com/shop Yes Only the path differs
http://www.example.com No Different scheme
https://api.example.com No Different host
https://www.example.com:8443 No Different port

The same-origin policy is the browser rule that keeps one origin's script from reading another's data. It matters because your browser holds your sessions. Without the rule, any page you visited could quietly request your webmail or banking pages with your cookies attached and read what came back.

Plenty of cross-origin loading is still ordinary. Pages can display images, apply stylesheets and run scripts from elsewhere, and forms can submit anywhere. The restriction bites when your code wants to read the content, typically with fetch or XMLHttpRequest, and also affects web fonts and pixel data drawn from other origins.

The simplest successful exchange

Say a page at https://www.example.com runs:

fetch("https://api.example.com/products")

The browser adds an Origin header stating where the page came from:

GET /products HTTP/1.1
Host: api.example.com
Origin: https://www.example.com

The API replies with permission:

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://www.example.com
Vary: Origin
Content-Type: application/json

The browser compares the two. If the allowed origin matches, the script receives the response. If the header is missing or different, the script gets a network error, and the explanation appears only in the console.

The value can also be *, meaning any origin may read it. That suits truly public data such as open fonts or a public read-only feed.

Preflight: asking permission first

Some requests could change data on a server that was never designed to expect them from other sites. For those, the browser asks first with a preflight.

A cross-origin request skips preflight only if it looks like something an old-fashioned HTML form could send: the method is GET, HEAD or POST, only a small set of headers are set by your code, and any Content-Type is application/x-www-form-urlencoded, multipart/form-data or text/plain. Sending JSON, adding an Authorization header or using PUT or DELETE all trigger a preflight.

A preflighted cross-origin request
Page script Browser API server PUT JSON to api.example.com 1 OPTIONS with Origin and intended method 2 204 listing allowed origin, method, headers 3 The real PUT request 4 Response with Allow-Origin header 5 Script may now read the result 6 Page script Browser API server PUT JSON to api.example .com 1 OPTIONS with Origin and intended method 2 204 listing allowed origin, method, headers 3 The real PUT request 4 Response with Allow-Origin header 5 Script may now read the result 6

The preflight looks like this:

OPTIONS /products/7 HTTP/1.1
Origin: https://www.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: content-type, authorization

And an approving answer:

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://www.example.com
Access-Control-Allow-Methods: GET, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 600
Vary: Origin

Access-Control-Max-Age lets the browser remember the approval for a while, saving a round trip. Browsers cap how long they will honor it.

Preflights carry no cookies or credentials. A server that demands a login on OPTIONS will reject every preflight, which is one of the most common causes of the error.

Credentials: cookies and logins

By default, fetch does not send cookies to another origin. To include them the page asks:

fetch("https://api.example.com/me", { credentials: "include" })

The server must then answer with both of these:

Access-Control-Allow-Origin: https://www.example.com
Access-Control-Allow-Credentials: true

The wildcard * is not accepted with credentials. The cookie also has to be eligible in its own right. Subdomains of one site count as the same site for SameSite purposes, while unrelated domains need SameSite=None; Secure and may still run into third-party cookie blocking. See how cookies work.

The headers in one place

Response header Purpose
Access-Control-Allow-Origin Which origin may read the response
Access-Control-Allow-Credentials Whether credentialed requests are permitted
Access-Control-Allow-Methods Methods approved at preflight
Access-Control-Allow-Headers Request headers approved at preflight
Access-Control-Max-Age How long to cache the preflight result
Access-Control-Expose-Headers Extra response headers scripts may read

The last one surprises people. A script can see only a few basic response headers cross-origin. If you return a pagination count or request ID in a custom header, list it in Access-Control-Expose-Headers.

What the console messages mean

Browsers word these differently, but the complaints fall into a few groups.

The message mentions What it usually means
No Access-Control-Allow-Origin header The response lacked permission, often an error page or an unconfigured route
The header has a value not equal to the origin Wrong scheme, host, port or a stray trailing slash
Multiple values Two layers each added the header
Preflight does not have HTTP ok status OPTIONS was rejected by routing, login or a firewall
Redirect is not allowed for preflight The address redirects, perhaps from HTTP to HTTPS or to add a slash
Request header field is not allowed A header you send is missing from Allow-Headers
Wildcard with credentials * was returned to a request that includes cookies

An allowed origin is written without a path or trailing slash: https://www.example.com, not https://www.example.com/.

Not every failed fetch is CORS. A server that is down, a certificate problem or a content blocker can produce a similarly vague error in the script. The browser deliberately tells your code very little, so that pages cannot probe other systems by reading error details. The console and Network tab, visible only to the person at the browser, say more.

Local development

Development setups run into CORS early, because a front end on http://localhost:3000 and an API on http://localhost:8000 are different origins. You have two tidy choices.

The first is to configure the API to allow the development origin, using a setting that applies only in development. The second is to use your development server's proxy feature, so the page calls its own origin and the tool forwards the request. The proxy avoids CORS during development, but make sure production uses the same arrangement, or the problem will reappear at launch.

Keep development origins out of the production allowlist. And avoid testing pages opened straight from disk with file:, which behave unlike anything your visitors will use. Run a small local web server.

Other places the rules appear

Several browser features reuse the same permission headers. A web font loaded from another origin needs Access-Control-Allow-Origin. So does an image you want to draw on a canvas and then read back, and the img element must also carry a crossorigin attribute. Script tags with subresource integrity checks on another origin need both as well.

If you serve files from a separate static host or storage service, look for its CORS settings screen. The vocabulary there matches the headers above, even when the form of the configuration differs.

Debugging an error

Tracking down a CORS failure
Did the OPTIONS preflight fail or redirect? YES Let OPTIONS succeed directly, without login or redirect. 1 NO Is Allow-Origin missing from the response? YES Add it on the target server, including on error responses. 2 NO Does it appear twice or differ from the page origin? YES Send exactly one value matching scheme, host and port. 3 NO Are cookies included while using a wildcard? YES Name the origin and allow credentials. 4 NO Check method and headers Compare the preflight request lists with what the server allows. Did the OPTIONS preflight fail or redirect? 1 IF YES Let OPTIONS succeed directly, without login or redirect. NO Is Allow-Origin missing from the response? 2 IF YES Add it on the target server, including on error responses. NO Does it appear twice or differ from the page origin? 3 IF YES Send exactly one value matching scheme, host and port. NO Are cookies included while using a wildcard? 4 IF YES Name the origin and allow credentials. NO Check method and headers Compare the preflight request lists with what the server allows.

Work in the Network tab, not only the console. Find the failing request and its preflight, and read the status codes. A 500 or 404 from the server often shows up as a CORS complaint, because the error page was produced without the headers.

You can also test from a terminal against your own API:

curl -i -X OPTIONS https://api.example.com/products/7 \
  -H "Origin: https://www.example.com" \
  -H "Access-Control-Request-Method: PUT" \
  -H "Access-Control-Request-Headers: content-type"

In Windows PowerShell, use curl.exe and put the command on one line. Note that curl will happily show you data from a request a browser would block, since it does not enforce CORS.

Configuring a server

The safe pattern for several allowed sites is an allowlist:

  1. Read the incoming Origin header.
  2. Compare it exactly against your list of permitted origins.
  3. If it matches, echo that value in Access-Control-Allow-Origin and add Vary: Origin.
  4. If it does not, send no CORS headers.

Vary: Origin matters because otherwise a cache or content delivery network might store the answer for one site and serve it to another.

Set the headers in one layer only. If both the application and the proxy add Access-Control-Allow-Origin, the browser sees two values and rejects the response.

Dangerous shortcuts

Reflecting any origin with credentials. Echoing whatever arrives and allowing cookies lets every website read your users' private data.

Loose matching. Checking that the origin merely contains or ends with your domain name can admit look-alike hosts.

Allowing null. Sandboxed frames and some local files send Origin: null, which anyone can produce.

Using mode: "no-cors". It silences the error by giving you an opaque response that your script cannot read.

Browser extensions or flags that disable the check. They only change your own browser and leave you exposed while enabled.

Avoiding CORS altogether

If you control both ends, serving the site and API from one origin removes the issue. A reverse proxy can forward /api/ on the main hostname to the API service. See reverse proxies. Another option is for your own server to call the third-party API and pass the result to your page, which also keeps secret API keys out of the browser.

Common questions

Does CORS protect my API from attackers?

No. Scripts, command-line tools and other servers ignore it entirely. Authentication, authorization and rate limits protect an API.

Why does it work in my API testing tool but not in the browser?

Testing tools are not browsers acting on behalf of a page, so they send no preflight and enforce no origin rules.

Did the server receive my blocked request?

For a request without preflight, usually yes, and it may have acted on it. Only reading the response was blocked. That is why state-changing actions also need anti-forgery protection.

Written for 4Internet with AI writing tools and not reviewed line by line by a person. Check anything you rely on with the maker, provider or standard concerned. Report an error.

Keep reading

All 45 articles in HTTP, TLS & Web Performance →

Latest news on this topic