DEV Community

Cover image for The Browser's Same-Origin Policy
perpetual uchechukwu
perpetual uchechukwu

Posted on

The Browser's Same-Origin Policy

Discovered mid-debug session, something oddly interesting..

The browser doesn't see http://localhost:5173 and http://127.0.0.1:5173/as the same website.

My jaws drooped for a while after I learnt this because localhost **is literally just a DNS for **127.0.0.1.

Probed further to understand why and I got insight in to one of the security protocols of browsers. The Same-Origin Policy (SOP).

The Same-Origin Policy is a critical browser security mechanism that restricts how documents or scripts from one origin can interact with resources from another origin. Two URLs are considered to have different origins if they differ in one or more of the following:

  • Scheme/protocol (http vs https)

  • Hostname (localhost vs 127.0.0.1)

  • Port (8080 vs 3000)

So since the hostnames are different, http://localhost:3000 and **http://127.0.0.1:3000 **are interpreted as completely different origins, even though they resolve to the same IP address.

This strict interpretation exists because the browser has no way to know that localhost and **127.0.0.1 **are the same thing.

When the browser compares both of them, it's essentially doing a simple string comparison:

Does the string "localhost" equal the string "127.0.0.1"?
No? Then they're different origins.

The browser doesn't perform DNS resolution or try to figure out that both resolve to the same IP address. It doesn't "look inside" the hostname to understand its meaning. To the browser:

localhost is just a string of characters
127.0.0.1 is a different string of characters
Therefore, they're different.

This simplicity prioritizes security over convenience, as it prevents potential attacks where a malicious site might try to exploit the assumption that different hostnames pointing to the same IP are interchangeable.

So at first, this felt like a bug. Like the browser was being unnecessarily stubborn. Why ignore what DNS exists for in the first place? But here's the plot twist: this "limitation" is actually a deliberate fortress. The browser chooses ignorance as armor. By refusing to be clever about hostname equivalence, it closes a door that attackers would love to pry open. What seemed like an oversight is actually security by design—purposefully blind, strategically simple, and surprisingly brilliant.

Interesting...

Top comments (0)