Security and Same-Origin Policy
You'll learn: How browser storage is protected by the same-origin policy and why this matters for security.
What is the Same-Origin Policy?
The same-origin policy is a critical security feature that restricts how web pages from different origins can access each other's data. When it comes to localStorage and sessionStorage, data is scoped entirely to its origin — a combination of three parts:
- Protocol (http vs https)
- Domain (example.com)
- Port (80, 443, 3000, etc.)
All three must match exactly for storage to be accessible.
Real-World Example
Imagine you visit https://bank.com and it stores your session token in localStorage. Without the same-origin policy, a malicious site like https://evil.com could read that token and impersonate you.
Thanks to the same-origin policy, https://evil.com cannot access storage from https://bank.com — they're different origins.
What Counts as Different Origins?
https://example.comvshttp://example.com— different (protocol)https://example.comvshttps://api.example.com— different (subdomain)https://example.com:443vshttps://example.com:3000— different (port)
Security Implications
Never store sensitive information (passwords, credit cards, private keys) in Web Storage — even with same-origin protection, storage is vulnerable to XSS attacks (malicious JavaScript injected into your page can read it).
Key Takeaway: Web Storage is scoped to origin (protocol + domain + port), preventing cross-site access, but isn't safe from XSS attacks within your own site—use secure, HTTP-only cookies for highly sensitive data.