Storage and browser security
What is an origin
Identify an origin from its scheme, host, and port and understand why paths do not create separate origins.
An origin is the combination of a URL’s scheme, host, and port. All three must match for two URLs to share an origin.
Why does the browser care? It needs a unit of isolation. Some rule that decides which pages belong together and may touch each other’s data, and which ones must be kept apart. The origin is that unit. Browsers use it for DOM access, for reading network responses, and for storage.
Take this URL:
https://shop.example.com:8443/account?tab=orders
Its origin is:
https://shop.example.com:8443
The path, the query string, and the fragment don’t count. So these two pages share an origin:
https://example.com/account
https://example.com/shop
And these four are all different origins:
http://example.com
https://example.com
https://app.example.com
https://example.com:8443
Each line fails a different part of the test. The first two differ in scheme. The third changes the host, and a subdomain counts as a completely different host. The fourth changes the port.
One detail about ports. When a URL omits the port, the scheme’s default applies. https://example.com and https://example.com:443 are the same origin, because 443 is the default for https. Writing the default explicitly changes nothing. Writing any other number creates a new origin.
Check an origin yourself
Open the Console on any page and run:
location.origin
You can also compute the origin of any URL without visiting it:
new URL('https://shop.example.com:8443/account?tab=orders').origin
// 'https://shop.example.com:8443'
I use this second form a lot when debugging. It’s faster than reasoning about the rules in my head.
The mistake to avoid
The common error is grouping URLs by domain name instead of origin. A subdomain is not trusted just because it belongs to the same parent domain. api.example.com and example.com are different origins, full stop.
We think “it’s all our domain, it will work”, and then the first cross-origin request or iframe access fails.
When that happens, compare the two origins with location.origin or new URL(...).origin and check the three parts one by one. Asking “do scheme, host, and port match?” is the first step in explaining most CORS and cross-window errors. The next lessons build directly on this definition.
Lesson completed