Skip to content

Web & Internet

CORS (Cross-Origin Resource Sharing)

O(1) per request — the check just tests whether one origin string appears on an allow-list.

The idea, in plain English

CORS (Cross-Origin Resource Sharing) is the rulebook that decides whether a website can fetch data from a different website's server. It works like a bouncer at a club checking a guest list before letting someone from another building's group in. Your browser is the bouncer. Before it lets a page's own code read data that came back from a different origin — a different domain, like api.example.com instead of mysite.com — it checks whether that server put the page's origin on an approved list.

How it works

  1. 1A page loaded from one origin, say https://mysite.com, tries to fetch data from a different origin's server, say https://api.example.com.
  2. 2The browser attaches the calling page's origin to the request, so the server can see exactly who is asking.
  3. 3The server checks its own list of allowed origins and decides whether to include the requester's origin in its response.
  4. 4If the requesting origin is on that allowed list, the browser lets the page's own code read the response. Otherwise, the browser blocks the page from reading it, even if the server already sent the data back.

When you'd use it

This applies to any web app whose JavaScript calls an API (Application Programming Interface) hosted on a different domain or subdomain than the page itself. That's the normal setup for a modern single-page app talking to a separate API server.

Common beginner mistakes

  • Don't think CORS stops the server from ever receiving the request. It doesn't. The server still gets it and can still act on it. CORS is enforced by the browser, and it only blocks the page's own JavaScript from reading the response.
  • Don't allow every origin just to make an error go away. It silences the browser's complaint, but throws away the entire point of the check, since now any website can read the API's responses.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Origin: https://mysite.com -> Access-Control-Allow-Origin: https://mysite.com -> page can read response: yes
Origin: https://admin.mysite.com -> Access-Control-Allow-Origin: https://admin.mysite.com -> page can read response: yes
Origin: https://evil.test -> Access-Control-Allow-Origin: none -> page can read response: no

Not sure this is the right topic? See the learning paths → or where this leads →