QuestionsBrowser

localStorage vs sessionStorage vs cookies

StorageEasyBrowser

Compare the three client storage mechanisms: capacity, lifetime, scope, and whether they're sent to the server.

What it tests

Whether you pick the right store and know cookies ride on every request.

Approach & answer

localStorage: ~5–10MB, key/value strings, persists until explicitly cleared, scoped to the ORIGIN, NOT sent to the server, synchronous API — good for user preferences and non-sensitive cached data. sessionStorage: same API and size, but scoped to a single TAB and cleared when that tab closes — good for per-tab wizard/form state. Cookies: tiny (~4KB each), and their defining trait is that the browser attaches matching cookies to EVERY HTTP request to the origin — which is exactly why they're used for session/auth tokens the server needs, but also why overusing them bloats every request. Cookies have an expiry (or are session cookies) and security attributes (HttpOnly, Secure, SameSite). Key contrasts: use localStorage/sessionStorage for client-only data you don't want on the wire; use cookies only for what the server must read on each request. Security note: anything readable by JS (localStorage, non-HttpOnly cookies) is exposed to XSS, so never store secrets there — auth tokens belong in HttpOnly cookies. For large or structured data, reach for IndexedDB (async, hundreds of MB). Storage values are always strings — JSON.stringify/parse objects.

Use this technique when

Choosing where to keep client state: prefs → localStorage, per-tab flow → sessionStorage, server-read session → cookie.

Code

// (Sandboxed here: storage/cookie access throws SecurityError, so this is read-only.)
localStorage.setItem('theme', 'dark');        // persists across tabs & restarts
console.log(localStorage.getItem('theme'));

sessionStorage.setItem('step', '2');          // dies when THIS tab closes
console.log(sessionStorage.getItem('step'));

document.cookie = 'sid=abc; max-age=3600; path=/'; // sent on every request to origin
console.log(document.cookie);

// objects must be serialized — storage only holds strings
localStorage.setItem('user', JSON.stringify({ id: 1, name: 'Ada' }));
console.log(JSON.parse(localStorage.getItem('user')).name);

References