All topics
Asyncintermediate

Web Storage vs Cookies for Async Data

How localStorage, sessionStorage, and cookies differ in capacity, lifetime, and how they interact with server requests, relevant when caching async fetch results client-side.

When client-side code needs to persist data between page loads — caching fetched API results, remembering preferences, storing a session token — there are three main browser storage mechanisms, and they differ enough that picking the wrong one causes real bugs and security issues.

localStorage is a filing cabinet in your own office that never gets cleaned until you do it. sessionStorage is a rented office cleared out when you leave. Cookies are a name badge you wear to every meeting automatically.

Key Concepts

1
localStorage persists with no expiration, surviving restarts, scoped per-origin, offering roughly 5-10MB, and is entirely synchronous. sessionStorage has an identical API but is scoped to a single tab's lifetime, useful for temporary, tab-specific state.
2
Cookies are capped at roughly 4KB each, are automatically attached to every matching HTTP request, and support expiration, domain/path scoping, and security flags like HttpOnly, Secure, and SameSite.
3
A common architecture caches fetch results in localStorage with a manually implemented expiration, while keeping auth tokens in an HttpOnly cookie, since JavaScript-accessible storage is vulnerable to theft via XSS, while HttpOnly cookies are not readable by injected scripts at all.