Storage & State in the Browser
The problem
A web page's in-memory JavaScript state disappears the moment the tab closes or reloads, but many things (login sessions, preferences, cart contents) need to persist across page loads — browsers provide several distinct storage mechanisms with different lifetimes, sizes, and network behavior for exactly this.
Why now
Variables and state already established in-memory bindings that vanish when a program ends; browser storage is the deliberate exception, giving specific, bounded mechanisms for persisting exactly the state you choose, for exactly as long as you choose, including whether it gets automatically sent to the server.
Mental model
Cookies are small and automatically attached to every matching HTTP request (which is what makes 'stay logged in' work, and also what makes them the right and wrong tool for different jobs). localStorage and sessionStorage are larger, never sent over the network automatically, and differ only in lifetime — localStorage persists indefinitely, sessionStorage dies with the tab.
Requires
- The HTTP Request Lifecycle in BrowsersBrowser Internals
Cookies are automatically attached to outgoing HTTP requests as part of the request lifecycle; you need to understand what's inside an HTTP request before 'automatically included in every request' is meaningful.
- Variables & StateProgramming Fundamentals
Every browser storage mechanism is fundamentally a name-to-value binding, like a variable, just with a persistence guarantee across reloads that an in-memory variable doesn't have.
Used in
- Session cookies keeping users logged in across page loads
- localStorage caching user preferences or offline-capable app data
- Shopping cart state surviving a page refresh via localStorage or sessionStorage
- Understanding third-party cookie restrictions and their privacy implications
Projects
- Store a user preference in localStorage, reload the page, and confirm it persists — then repeat with sessionStorage and close/reopen the tab to observe the difference
- Inspect a real website's cookies in DevTools and identify which ones look session-related versus tracking-related, and explain your reasoning
Examples
- A login session cookie is automatically sent with every subsequent request to the same domain, which is exactly how 'stay logged in' works without extra code
- localStorage.setItem('theme', 'dark') persists across reloads and browser restarts until explicitly cleared
Resources
- MDN — Client-side storagearticle
Mastery checklist
- I can explain the difference between cookies, localStorage, and sessionStorage
- I can explain why cookies are automatically sent with requests but localStorage is not
- I can choose the appropriate storage mechanism for a given persistence requirement
- I can inspect and modify stored data for a real page using browser DevTools