What is the same-origin policy?
SecurityThe short answer
The same-origin policy is a browser security rule that prevents JavaScript on one website from accessing data on another website. Two URLs have the same origin if they share the same protocol, domain, and port. Without this policy, any website could read your emails, bank data, or any other page you are logged into.
What counts as "same origin"
An origin is defined by three parts: protocol + domain + port.
| URL | Same origin as https://example.com? |
|---|---|
https://example.com/page | Yes — same protocol, domain, port |
https://example.com:443/page | Yes — 443 is the default HTTPS port |
http://example.com | No — different protocol (http vs https) |
https://api.example.com | No — different domain (subdomain counts) |
https://example.com:8080 | No — different port |
What it restricts
The same-origin policy restricts:
- AJAX/fetch requests — JavaScript cannot read responses from a different origin (without CORS)
- DOM access — JavaScript cannot access the DOM of a page in an iframe from a different origin
- Cookies — Cookies are scoped to their domain and cannot be read by other origins
- localStorage/sessionStorage — Scoped to the origin
What it does NOT restrict
- Loading resources — You can load images, scripts, stylesheets, and fonts from any origin
- Form submissions — Forms can submit to any URL
- Embedding — You can embed iframes, videos, and other content from any origin
This is an important distinction. You can load a script from another domain, but you cannot read its content with JavaScript. You can embed an iframe, but you cannot access its DOM.
CORS — the official workaround
When you need cross-origin requests (like calling an API on a different domain), the server must enable CORS (Cross-Origin Resource Sharing):
Access-Control-Allow-Origin: https://your-site.comThis header tells the browser "I allow requests from this origin." Without it, the browser blocks the response.
postMessage — for iframe communication
For cross-origin iframe communication, use postMessage:
// Send a message to a cross-origin iframeiframe.contentWindow.postMessage( data, 'https://other-domain.com');Both sides must agree to communicate. The receiver always checks event.origin.
Interview Tip
Explain the three parts of an origin (protocol, domain, port) with examples. Then explain what is restricted and what is not. Mentioning CORS as the solution for cross-origin API calls shows practical knowledge.
Why interviewers ask this
The same-origin policy is fundamental to web security. Interviewers ask about it to see if you understand why cross-origin requests fail, how CORS fixes it, and why the browser enforces these restrictions. This is essential knowledge for anyone building web applications that talk to APIs.