Same-Origin Policy and JavaScript Network Requests

The Same-Origin Policy (SOP) is a foundational web security model that restricts how a document or script loaded by one origin can interact with a resource from another origin. In JavaScript, this policy dictates whether network requests initiated by APIs such as fetch() or XMLHttpRequest can access and read the responses returned by external servers. This article explains what constitutes an origin, how SOP restricts cross-origin network operations, and the standard mechanisms used to safely bypass these restrictions.

What Defines an Origin?

An origin is defined by the combination of three components: 1. Protocol (Scheme): e.g., http:// vs. https:// 2. Host (Domain): e.g., example.com vs. api.example.com 3. Port: e.g., :80, :443, or :3000

Two URLs share the same origin only if all three components match exactly. For example, https://example.com/page1 and https://example.com/page2 have the same origin, whereas http://example.com and https://example.com do not.

How SOP Governs JavaScript Network Requests

The primary purpose of SOP in JavaScript is to prevent malicious scripts on one site from reading sensitive data from another site without authorization. The policy applies specific rules to network interactions:

Cross-Origin Resource Sharing (CORS)

Cross-Origin Resource Sharing (CORS) is the standard mechanism that allows servers to selectively relax SOP restrictions for JavaScript requests. When a JavaScript request is made to a different origin, the browser and server communicate using HTTP headers:

Other Mechanisms Interacting with SOP