Episode 1 — Fundamentals / 1.16 — Using Browser Functionalities in JavaScript

1.16.c — Web Storage (localStorage / sessionStorage) & Cookies

In one sentence: localStorage and sessionStorage are 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
localStoragesessionStorage
LifetimeUntil explicitly removedTab lifetime — cleared when tab/window closes
ScopeSame origin across tabsPer 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.

StorageSent automatically on HTTP?Typical max size
localStorage / sessionStorageNoMegabytes
CookiesYes (unless HttpOnly — then not readable from JS)~4 KB per cookie (rough)

HttpOnly cookiesnot 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 localStorage without understanding risk — tokens in memory or HttpOnly cookies are common patterns.
  • SameSite on cookies reduces CSRF risk (see HTTP lessons).
  • Only store non-sensitive preferences in localStorage unless you have a threat model.

6. Key takeaways

  1. localStorage = persistent per origin; sessionStorage = per tab.
  2. Values are strings — serialize objects as JSON.
  3. 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:

  1. When would you choose sessionStorage over localStorage?
  2. Why is document.cookie awkward compared to getItem / setItem?
  3. Why can HttpOnly cookies be safer than a JWT in localStorage against XSS?

Navigation: ← 1.16.b — Location & History · 1.16.d — Fetch API →