Web Development

Same-Origin Policy: Browser Security and Usage Guide

Understand the Same-Origin Policy (SOP) and how it protects data. Define origin tuples, compare SOP vs CORS, and manage cross-origin access.

2.9k
same-origin policy
Monthly Search Volume

The Same-Origin Policy (SOP) is a core security protocol built into all modern web browsers. It restricts how a script or document from one origin can interact with data from a different origin to prevent malicious sites from accessing sensitive user information. For SEO practitioners and marketers, understanding SOP is essential when managing multiple subdomains, tracking codes, or third-party APIs that may fail due to browser security restrictions.

What is Same-Origin Policy?

SOP acts as a wall between different websites. If you are logged into your bank in one tab and visit a blog in another, SOP prevents the blog from running a script to read your bank details or session cookies.

Browsers determine if two pages are the "same origin" based on a three-part identifier known as a "tuple" (or scheme/host/port tuple). Two URLs must match all three elements exactly:

  1. Protocol (Scheme): (e.g., http vs https)
  2. Host (Domain): (e.g., example.com vs blog.example.com)
  3. Port: (e.g., port 80 vs port 8080)

Origin Comparison Examples

Using http://store.company.com/dir/page.html as the base:

URL Result Reason
http://store.company.com/dir2/other.html Success Same scheme, host, and port
https://store.company.com/page.html Failure Different protocol (HTTPS)
http://news.company.com/dir/page.html Failure Different host
http://store.company.com:81/dir/page.html Failure Different port

Special cases exist for [Netscape Navigator 2.02, which first introduced the policy in 1995] (Wikipedia). For example, Internet Explorer historically ignored the port number when checking origins.

Why Same-Origin Policy matters

SOP is the primary defense against data theft and session hijacking. Without it, the "World Wide Web" would lack the necessary separation to keep personal data private.

  • Protects Authenticated Sessions: It prevents malicious sites from sending requests to other sites using your saved session cookies.
  • Ensures Data Confidentiality: Scripts on one site cannot "read" the content of an iframe or a response from another site.
  • Prevents Cross-Site Request Forgery (CSRF): By blocking unauthorized reads, it limits the ability of attackers to perform actions on your behalf.
  • Maintains Tracking Integrity: It ensures that marketing scripts only access data from authorized domains, though this often requires specific setup via CORS.

How Same-Origin Policy works

SOP does not block every interaction; it specifically controls reads.

Allowed: Cross-Origin Writes and Embedding

The policy generally permits a site to send data or embed resources from other origins. This is why you can still use: * Images: via the <img> tag. * Scripts: via <script src="..."></script>. * CSS: via <link rel="stylesheet">. * Multimedia: via <video> or <audio>. * Forms: You can submit a form to another domain, though the script cannot read the result.

Blocked: Cross-Origin Reads

A script from site-a.com cannot use a fetch or XMLHttpRequest to read the data returned from site-b.com unless site-b.com explicitly allows it. While you can embed a cross-origin image, your JavaScript cannot read the raw pixel data of that image unless specific permissions are granted.

How to allow cross-origin access

Marketers often need to bypass SOP to share data between a main site and a subdomain or to load content from a third-party tool.

Cross-Origin Resource Sharing (CORS)

CORS is the modern standard for relaxing SOP. It uses HTTP headers to tell the browser that a specific origin is trusted. When a "non-simple" request is made, the browser sends a "preflight" request using the OPTIONS method. [If the server allows the action, the preflight response can be cached for a maximum of 86400 seconds] (Emrebener) to avoid repeated checks, though [the default cache is often 5 seconds] (Emrebener).

PostMessage

To communicate between an iframe and its parent page across different domains, use window.postMessage. This allows the two windows to send text messages to each other without directly accessing each other's DOM.

Best practices

Use subdomains for different services. Separate your web services by subdomains (e.g., api.example.com and blog.example.com) rather than ports. SOP treats different ports as different origins, but cookies are often shared across subdomains.

Implement CSRF tokens. Since SOP allows cross-origin "writes" (like form submissions), always use an unguessable token in your forms to verify the request came from your own site.

Leverage CSP. Use Content Security Policy (CSP) headers to restrict which domains are allowed to embed your resources, providing an extra layer of protection beyond SOP.

Verify WebSocket origins. Browsers do not apply SOP to WebSockets. The server must manually check the Origin header to ensure the connection is authorized.

Common mistakes

Mistake: Assuming HTTPS and HTTP are the same origin. Fix: Always use HTTPS for all resources. A move from http://example.com to https://example.com is a change in origin and will break scripts that rely on same-origin access.

Mistake: Relying on the document.domain setter. Fix: Avoid this method. Using document.domain to allow subdomains to talk to each other is deprecated because it weakens security and causes interoperability issues.

Mistake: Using ports to separate secure and insecure data. Fix: Do not host sensitive data on the same host using a different port. Cookies do not always respect port-based isolation, which can lead to session leaks.

Mistake: Forgetting that "embedding" leaks information. Fix: If a resource is sensitive, ensure it cannot be embedded. Even if a script cannot read the data, it can often infer information like image dimensions or whether a resource exists.

SOP vs CORS

Feature Same-Origin Policy (SOP) Cross-Origin Resource Sharing (CORS)
Goal Restrict access to safeguard data. Relax restrictions for trusted sites.
Default State Enabled in all modern browsers. Disabled unless configured on server.
Logic Blocks "reads" by default. Uses headers to permit "reads."
Control Browser-enforced. Server-configured.

FAQ

Can I disable the Same-Origin Policy? You cannot disable SOP in a user's browser. It is a fundamental safety feature. To allow your own scripts to communicate across origins, you must implement CORS headers on your server or use postMessage.

Why does my tracking script work if it's on a different domain? The SOP allows cross-origin embedding. When you add a <script src="tracking-tool.com/script.js"> tag to your site, the browser executes the script. The script then runs under your site's origin, allowing it to read your page's data, but it cannot read data from tracking-tool.com unless CORS is enabled there.

Does SOP apply to cookies? Cookies use a slightly different definition. They are often accessible across subdomains of the same parent domain. To protect cookies, use the HttpOnly and Secure flags, as SOP is more relaxed regarding cookie access than it is for DOM or AJAX requests.

How do "about:blank" pages handle origins? A popup or iframe with an about:blank URL inherits the origin of the document that created it. This allows the parent script to write content into the new window and still satisfy same-origin requirements.

What is a preflight request? A preflight is an automatic check the browser performs before a "complex" request (like a PUT or a request with custom headers). It uses the OPTIONS HTTP method to ask the server if the cross-origin request is permitted before actually sending the data.

Start Your SEO Research in Seconds

5 free searches/day • No credit card needed • Access all features