Skip to content
Tutorials Center
My learning

Topics

Lesson 98 of 122 ยท Web APIs

Cross-Origin Requests and CORS

Understand the same-origin policy and CORS. Learn simple and preflighted requests, credentials, opaque responses, the crossorigin attribute and how to read CORS errors.

Sooner or later every web developer sees this in the console: a request that "has been blocked by CORS policy". The request reached the server, the server answered, and yet your JavaScript gets nothing but a vague error. It feels like the browser is fighting you.

It is actually protecting your users. In this lesson you will learn the rule behind the error, the same-origin policy, and the way servers relax it on purpose, Cross-Origin Resource Sharing (CORS). You will see which requests need a preflight, how cookies change the rules, what the crossorigin attribute on <img>, <script> and <video> does, and why CORS errors are so unhelpful by design.

The same-origin policy

An origin is the scheme, host and port of a URL. Two URLs have the same origin only if all three match:

URL Same origin as https://shop.example?
https://shop.example/cart?id=4 Yes: path and query don't count
http://shop.example No: different scheme
https://api.shop.example No: different host (subdomains count)
https://shop.example:8443 No: different port

The browser's same-origin policy lets a page use resources from other origins but not read them. That distinction explains almost everything:

  • Embedding is allowed. <img>, <script src>, stylesheets, <video> and iframes load from anywhere. The browser displays or runs them, but your script can't look inside.
  • Sending is mostly allowed. A form can post to another site, and fetch() can send a simple request to any URL.
  • Reading the response is blocked unless the other origin agrees.

Why? Because the browser attaches the user's cookies to requests. If any site could fetch("https://bank.example/account") and read the answer, every page you visit could read your bank balance with your login. The same-origin policy stops that by keeping the response away from the page that asked.

The URL API can tell you the origin of any address, so you can check the rules yourself:

Comparing origins

Note that :443 disappears from the origin, because it is the default port for https. And this preview reports its own origin as "null": the examples on this site run in a sandbox with an opaque origin, which is cross-origin to everything, including our own server.

What CORS does

CORS is a set of HTTP headers that let a server say "this other origin may read my response". The conversation looks like this (read-only examples; the browser sends the Origin header for you):

HTTP
GET /api/weather?city=Lisbon HTTP/1.1
Host: api.weather.example
Origin: https://travel.example
HTTP
HTTP/1.1 200 OK
Content-Type: application/json
Access-Control-Allow-Origin: https://travel.example
Vary: Origin

{"city":"Lisbon","temp":19}

When the response arrives, the browser compares Access-Control-Allow-Origin with the page's origin. If they match, or the value is *, your script receives the response. If the header is missing or different, the browser throws the response away and rejects your fetch() promise.

Three things follow from this:

  • CORS is enforced by the browser, not the server. The server already did its work and sent the data. Tools like curl ignore CORS completely.
  • CORS loosens security; it never adds any. The same-origin policy is the protection, and CORS is the controlled exception.
  • Only the server can fix a CORS error. Nothing you write in the page can grant your own page permission to read someone else's data.

Vary: Origin tells caches that the answer depends on the Origin header, so a cached response allowed for one site is not served to another. Send it whenever you echo back a specific origin.

Simple requests and preflights

For some requests the browser just sends them and checks the answer afterwards. These are simple requests, and they match what an old-fashioned HTML form could already send:

  • The method is GET, HEAD or POST.
  • The only headers you set are "safelisted" ones such as Accept, Accept-Language, Content-Language and Content-Type.
  • Content-Type, if set, is text/plain, application/x-www-form-urlencoded or multipart/form-data.

Anything else (a PUT or DELETE, a JSON body with Content-Type: application/json, an Authorization header, any custom header) could do things a form never could. For those, the browser first asks permission with a preflight: an automatic OPTIONS request with no body.

HTTP
OPTIONS /api/orders/17 HTTP/1.1
Origin: https://admin.shop.example
Access-Control-Request-Method: DELETE
Access-Control-Request-Headers: authorization
HTTP
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://admin.shop.example
Access-Control-Allow-Methods: GET, POST, DELETE
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Max-Age: 600

Only if the preflight answer allows the origin, method and headers does the browser send the real DELETE. Access-Control-Max-Age lets it cache that permission (here for 600 seconds) so the next request skips the extra round trip. Browsers cap this value, at two hours in Chromium, for example.

The preflight decision is mechanical, so you can model it in a few lines. Try adding your own requests to the list:

Will this request be preflighted?

The real rules have a few extra limits (for example on header value lengths and characters), but this captures the idea. Notice how the most common API call, a JSON POST, is always preflighted.

Cookies and credentials

By default, a cross-origin fetch() sends no cookies and ignores any Set-Cookie in the response. To include them, the page must ask explicitly:

JavaScript
const response = await fetch("https://api.shop.example/cart", {
  credentials: "include",
});

And the server must agree with stricter headers:

HTTP
Access-Control-Allow-Origin: https://shop.example
Access-Control-Allow-Credentials: true
Vary: Origin

With credentials, the wildcard is not allowed: Access-Control-Allow-Origin: * is rejected, and so are * in Allow-Headers and Allow-Methods. The server must name the exact origin. This is deliberate. "Any site may read this user's private data" is never what you want.

Cookies have their own rules too. A cookie marked SameSite=Lax or Strict is not sent on cross-site fetch() requests at all, even with credentials: "include". Cross-site cookies need SameSite=None; Secure, and many browsers now block or partition third-party cookies anyway. For APIs used from other sites, a token in the Authorization header is often simpler.

Reading response headers

Even after a successful CORS request, your script can only read a few "safelisted" response headers, such as Content-Type, Content-Length, Cache-Control and Last-Modified. To share another header, the server lists it:

HTTP
Access-Control-Expose-Headers: X-Total-Count, ETag

Why CORS errors look the way they do

When CORS blocks a response, your code sees only this:

JavaScript
try {
  const response = await fetch("https://api.other.example/data");
} catch (error) {
  console.log(error.name);    // "TypeError"
  console.log(error.message); // "Failed to fetch" (wording varies by browser)
}

No status code, no headers, no hint about what went wrong. That vagueness is a security feature. If JavaScript could tell "blocked by CORS" apart from "server not found" or "connection refused", a hostile page could probe the user's private network ("is there a router at 192.168.1.1?") and learn which internal sites exist. So every failure looks the same to the page.

The details go to the DevTools console, which only the user sees. When you debug:

  1. Read the console message. It names the missing or wrong header.
  2. Open the Network panel. You will often see the request completed with status 200: the server answered, the browser refused to hand it over. Look for a failed OPTIONS preflight too.
  3. Check the response headers against the request: origin spelled exactly (scheme, host and port, no trailing slash), methods and headers listed, credentials rules followed.
  4. Remember that error responses need CORS headers too. If your server only adds them to 200 responses, a 500 will show up as a CORS error and hide the real problem.

no-cors is not a fix

You may find advice to add mode: "no-cors" to fetch(). It makes the error disappear, but only because the browser gives you an opaque response instead:

JavaScript
const response = await fetch("https://api.other.example/data", { mode: "no-cors" });
console.log(response.type);   // "opaque"
console.log(response.status); // 0
console.log(await response.text()); // "": the body is hidden

An opaque response has no readable status, headers or body. It is useful in one niche, caching third-party files in a service worker, and useless for reading data. The only real fixes are to add CORS headers on the server, or to call the API from your own server (a proxy), where the same-origin policy does not apply.

The crossorigin attribute

Elements that load files, <img>, <video>, <audio>, <script> and <link>, normally fetch them in "no-cors" mode. That's why embedding works without any headers. Adding the crossorigin attribute switches the element to a CORS request:

HTML
<img src="https://cdn.example/photo.jpg" crossorigin="anonymous" alt="Harbor at dawn">
<script src="https://cdn.example/app.js" crossorigin="anonymous"></script>
<video src="https://media.example/clip.mp4" crossorigin="use-credentials" controls></video>
  • anonymous (or an empty crossorigin): a CORS request without cookies.
  • use-credentials: a CORS request with cookies, which needs Access-Control-Allow-Credentials: true and an exact origin.

Why ask for CORS when the image displays fine without it? Because some features need to read the file, not just show it:

  • Canvas pixels. Drawing a cross-origin image without CORS onto a canvas "taints" it, and getImageData() or toDataURL() throws a SecurityError.
  • Script errors. Errors from a cross-origin script without CORS reach window.onerror only as "Script error.", with no message or line.
  • Subresource Integrity. An integrity hash on a cross-origin script or stylesheet only works with crossorigin (see Resource Loading).
  • Text tracks. A cross-origin <track> file for a <video> must be loaded with CORS (see Captions and Subtitles).

Some loads are always CORS: web fonts from another origin, module scripts (<script type="module">) and fetch() itself.

The catch: once you add crossorigin, the server must send CORS headers, or the file fails to load completely. The next example runs in our opaque-origin sandbox, so even our own sample image counts as cross-origin. It shows both outcomes:

A tainted canvas

The first canvas is always readable. The second shows the image but throws when you read it. The third depends on the server: if it sends Access-Control-Allow-Origin for the image, the pixels are readable; if not, the image does not load at all. (The ?cors query only makes the URL different, so the browser cannot reuse the non-CORS copy from its cache.)

A server-side checklist

You will configure CORS in your server or framework, not in HTML, but the decisions are the same everywhere:

  • List exact origins you trust, and echo the request's Origin only if it is on that list. Avoid reflecting any origin blindly; that is the same as *, but with credentials.
  • Use * only for truly public, cookie-free data, such as open datasets or fonts.
  • Answer OPTIONS preflights with the allowed methods and headers, and set a sensible Access-Control-Max-Age.
  • Add Vary: Origin when the allowed origin changes per request.
  • Remember that CORS does not stop requests from being sent. Protect state-changing endpoints against cross-site request forgery with tokens and SameSite cookies.

A minimal static-file rule in nginx, for example, looks like this:

NGINX
location /fonts/ {
  add_header Access-Control-Allow-Origin "*";
}

Cross-origin rules also govern how windows talk to each other. You saw that side in Cross-Document Messaging with postMessage.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these URLs has the same origin as https://shop.example/home?

    Paths and query strings don't count. A different scheme, subdomain or port makes a different origin.
  2. 2. A fetch() sends JSON with Content-Type: application/json to another origin. What happens first?

    A JSON content type is not one of the three simple types, so the browser asks permission with a preflight before sending the real request.
  3. 3. A page uses credentials: "include" and the server replies with Access-Control-Allow-Origin: *. What does the page get?

    With credentials, the wildcard is rejected. The server must name the origin and send Access-Control-Allow-Credentials: true.
  4. 4. Why does JavaScript only see a generic TypeError when CORS blocks a request?

    The vagueness is deliberate. Detailed reasons appear in DevTools for the developer, but not to scripts, which could otherwise map out networks they should not see.
  5. 5. What does adding crossorigin="anonymous" to an <img> change?

    The attribute turns the load into a CORS request without cookies. With the right server headers, the canvas stays untainted; without them, the image does not load.

Summary

  • An origin is scheme + host + port. The same-origin policy lets pages embed and send across origins, but not read the responses.
  • CORS is how a server opts in: Access-Control-Allow-Origin names who may read the response, and Vary: Origin keeps caches honest.
  • Non-simple requests (other methods, JSON, custom headers) are preceded by an OPTIONS preflight, which Access-Control-Max-Age can cache.
  • Cookies need credentials: "include", Access-Control-Allow-Credentials: true and an exact origin, never *.
  • CORS failures appear to scripts as a generic TypeError on purpose; the real reason is in DevTools. no-cors only gives you an unreadable opaque response.
  • The crossorigin attribute makes images, media and scripts load with CORS, which canvas reads, error details, SRI and text tracks need.

Next lesson: Accessibility Basics, where you make sure everything you build works for everyone.