Episode 1 — Fundamentals / 1.16 — Using Browser Functionalities in JavaScript
1.16.c — Web Storage (localStorage / sessionStorage) & Cookies
In one sentence:
localStorageandsessionStorageare simple key–value stores per origin; cookies are smaller name=value strings sent on HTTP requests — choose the tool by lifetime, size, and server visibility.
Navigation: ← 1.16.b — Location & History · 1.16.d — Fetch API →
1. Web Storage API
Both are Storage objects on window:
localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme");
localStorage.removeItem("theme");
localStorage.clear(); // wipe all keys for this origin
localStorage | sessionStorage | |
|---|---|---|
| Lifetime | Until explicitly removed | Tab lifetime — cleared when tab/window closes |
| Scope | Same origin across tabs | Per tab (same origin) |
| Capacity | ~5–10 MB typical (browser-dependent) | Similar order |
Origin = scheme + host + port. http://a.com and https://a.com are different origins.
2. Storage values are strings
localStorage.setItem("count", 1); // coerced to "1"
const n = Number(localStorage.getItem("count"));
For objects, use JSON.stringify / JSON.parse and handle try/catch for corrupt data.
3. Synchronous API
localStorage I/O is synchronous — large writes on the main thread can jank the UI. For heavy client data prefer IndexedDB (later course) or server persistence.
4. Cookies (document.cookie)
Cookies are text associated with an origin (and optional path, domain, Secure, HttpOnly, SameSite — many attributes are set by server Set-Cookie header).
From JavaScript:
document.cookie = "sessionId=abc123; path=/; max-age=3600";
Reading document.cookie returns all visible cookies as one semicolon-separated string — awkward to parse.
| Storage | Sent automatically on HTTP? | Typical max size |
|---|---|---|
localStorage / sessionStorage | No | Megabytes |
| Cookies | Yes (unless HttpOnly — then not readable from JS) | ~4 KB per cookie (rough) |
HttpOnly cookies — not accessible to document.cookie — good for session tokens to mitigate XSS theft (still need CSRF protections for mutating requests).
5. Security notes (brief)
- Never store secrets that XSS can read in
localStoragewithout understanding risk — tokens in memory orHttpOnlycookies are common patterns. SameSiteon cookies reduces CSRF risk (see HTTP lessons).- Only store non-sensitive preferences in
localStorageunless you have a threat model.
6. Key takeaways
localStorage= persistent per origin;sessionStorage= per tab.- Values are strings — serialize objects as JSON.
- Cookies are for small, server-visible state; Web Storage stays in the browser until you send it explicitly (e.g. with
fetch).
Explain-It Challenge
Explain without notes:
- When would you choose
sessionStorageoverlocalStorage? - Why is
document.cookieawkward compared togetItem/setItem? - Why can
HttpOnlycookies be safer than a JWT inlocalStorageagainst XSS?
Navigation: ← 1.16.b — Location & History · 1.16.d — Fetch API →