JavaScript Reference ยท Browser and Web APIs
The same-origin policy and CORS
Concept page: what an origin is, what the same-origin policy blocks, how CORS headers and preflight requests relax it, and how to debug common CORS errors.
Every page you open can run JavaScript, and many of your open tabs are logged in to something: mail, banking, work tools. If any script on any page could freely read responses from any other site using your cookies, the web would be unusable. The same-origin policy is the browser's core defense: a page may freely send many kinds of requests, but scripts may only read responses from the same origin as the page itself.
CORS (Cross-Origin Resource Sharing) is the controlled loosening of that rule. A server can say, in HTTP headers, "scripts from this other origin may read my responses".
What is an origin?
An origin is the combination of scheme, host and port. Two URLs are same-origin only when all three match. Paths, queries and fragments do not matter.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
What the policy blocks
- Reading cross-origin responses from
fetch()andXMLHttpRequest, unless CORS allows it. - Reading another origin's DOM through an
<iframe>orwindow.open()reference, or its cookies and storage. Storage such aslocalStorageis separate for each origin. - Reading pixels of a canvas that was tainted by a cross-origin image drawn without CORS permission.
What it does not block: embedding images, scripts, stylesheets and frames from other origins (you just cannot read their contents from script), submitting a form to another site, and following links. This is why separate defenses such as CSRF tokens and SameSite cookies exist.
How CORS works
For a "simple" request, the browser sends the request with an Origin header and looks at the response. If the response has Access-Control-Allow-Origin matching your origin (or *), the script may read it; otherwise the browser withholds the response and logs a CORS error. The request still reached the server, so CORS protects readers, not servers.
For anything else (methods such as PUT or DELETE, a JSON Content-Type, custom headers) the browser first sends a preflight: an OPTIONS request that asks permission, with Access-Control-Request-Method and Access-Control-Request-Headers. The server answers with Access-Control-Allow-Methods and Access-Control-Allow-Headers, and may add Access-Control-Max-Age so the browser can cache the answer. Only then is the real request sent.
Cookies and other credentials are not sent cross-origin by default. You must opt in with fetch(url, { credentials: "include" }), and the server must answer with Access-Control-Allow-Credentials: true and a specific origin: * is not accepted together with credentials.
The next example models the browser's decision so you can see the rules. It is a simulation: real checks happen inside the browser, and a sandboxed preview cannot make network requests.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Usage notes
- Fix CORS on the server, not the client. No front-end code can grant itself permission. Add the right response headers on the API (or proxy the call through your own server).
no-corsmode is not a fix.fetch(url, { mode: "no-cors" })produces an opaque response you cannot read.- A CORS error in the console can hide the real status. The server may have returned a 500 without CORS headers, which then looks like a CORS failure. Check the Network tab.
- Do not reflect any
Originblindly. Echoing whatever origin the request sends, together with credentials, defeats the protection. Use an allow-list. Vary: Originshould be sent when the allowed origin changes per request, so caches do not mix responses.- Other cross-origin tools:
window.postMessage()for messaging between windows (always checkevent.origin), andCross-Origin-Opener-Policy/Cross-Origin-Embedder-Policyheaders for stricter isolation. - Same-site is not same-origin.
app.example.comandapi.example.comare the same site (for cookie purposes) but different origins.
Browser support
The same-origin policy and CORS are implemented consistently in all browsers. Details of newer related features, such as cross-origin isolation headers and Private Network Access, vary, so check a compatibility table.
Related
- fetch(), URL
- Content Security Policy
- document.cookie
- Lessons: Security, Fetch, Cookies