What Is Same Origin Policy
On This Page
FAQs
The same-origin policy (SOP) is a web browser security feature that restricts how documents and scripts from one website (origin) can interact with resources on another. In simple terms, it prevents a malicious site from accessing data on another site through the browser, protecting users from threats like cross-site scripting (XSS) or data leaks. (It’s like a privacy fence between websites.)
SOP helps enforce web privacy and application isolation. Without it, any website could make unauthorized requests or read sensitive information from other websites you’re logged into, such as banking portals or email accounts. It’s a core defense against cross-origin attacks like CSRF and credential theft.
In the context of SOP, “origin” refers to a unique combination of protocol (HTTP/HTTPS), domain, and port. For two web pages to be considered of the same origin, all three elements must match exactly. For example, https://example.com and http://example.com are different origins due to the protocol.
Same-origin policy can be bypassed or relaxed under certain conditions, such as:
Using CORS (Cross-Origin Resource Sharing) headers from the server
PostMessage API for safe cross-origin communication
(Historically) using document.domain, although it’s now deprecated due to security risks Improper use of these methods can lead to vulnerabilities or unauthorized access.
The same-origin policy is a default browser-enforced restriction, while CORS is a way for servers to explicitly allow certain cross-origin requests using headers like Access-Control-Allow-Origin. SOP blocks by default; CORS provides controlled exceptions when configured securely.
To prevent cross-origin attacks:
Use strict and validated CORS policies
Avoid Access-Control-Allow-Origin: * unless absolutely necessary
Implement CSRF tokens
Sanitize and validate all inputs to prevent XSSUse security headers like Content-Security-Policy, X-Frame-Options, and SameSite cookies
These practices complement the same-origin policy to create layered browser security.