Course contentsShow
← Web Development
Lesson 778 of 2,98214. Browser StorageFree lesson

Security and Same-Origin Policy

Understanding that storage is scoped to origin (protocol, domain, port) and security implications.

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:

  1. Protocol (http vs https)
  2. Domain (example.com)
  3. 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.com vs http://example.com — different (protocol)
  • https://example.com vs https://api.example.com — different (subdomain)
  • https://example.com:443 vs https://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.