DOM & Browser APIs
Web Storage
Browsers provide three main ways to persist data on the client: localStorage,sessionStorage, and cookies. Each has different lifetimes, scopes, and use cases.
How do you use localStorage in JavaScript?
localStorage.setItem("key", "value") saves a string that survives page reloads and browser restarts, getItem("key") reads it back (or returns null), and removeItem deletes it. It only stores strings, so convert objects with JSON.stringify and back with JSON.parse. sessionStorage has the same API but is cleared when the tab closes.
localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme") ?? "light";
const save = (k, v) => localStorage.setItem(k, JSON.stringify(v));
const load = (k, fallback) => {
try { return JSON.parse(localStorage.getItem(k)) ?? fallback; }
catch { return fallback; }
};
window.addEventListener("storage", (e) => { /* changed in another tab */ });Storage Comparison
| Feature | localStorage | sessionStorage | Cookie |
|---|---|---|---|
| Capacity | ~5 MB | ~5 MB | ~4 KB |
| Persistence | Forever | Tab lifetime | Configurable |
| Server access | ❌ | ❌ | ✅ (HTTP header) |
| Shared across tabs | ✅ | ❌ | ✅ |
| HTTP-only flag | ❌ | ❌ | ✅ |
| Expiry control | Manual clear | Auto on close | max-age / expires |
| JS accessible | ✅ | ✅ | ✅ (unless httpOnly) |
| Works in SW | ❌ | ❌ | ❌ |
localStorage / sessionStorage API
localStorage.setItem(key, value)Store a string valuelocalStorage.getItem(key)Returns string or nulllocalStorage.removeItem(key)Delete one entrylocalStorage.clear()Delete ALL entrieslocalStorage.key(index)Get key by index (for iteration)localStorage.lengthNumber of stored entriesJSON.stringify(obj)Serialize before storing objectsJSON.parse(str)Deserialize after reading objectsCommon Pitfalls
Storing objects directly — localStorage.setItem('user', { name: 'A' }) stores '[object Object]'
Always JSON.stringify before storing and JSON.parse after reading
Storing sensitive data (tokens, passwords) in localStorage — accessible via XSS
Store auth tokens in httpOnly cookies (server-set) so JavaScript cannot access them
Expecting localStorage to exist in every environment — SSR (Node.js) throws ReferenceError
Guard with typeof localStorage !== 'undefined' or use a try/catch when running in SSR contexts
Assuming QuotaExceededError won't happen — 5 MB fills up quickly with large objects
Wrap setItem in a try/catch and handle QuotaExceededError by evicting old data
Interactive Storage Explorer
Code Editor
<label>Theme <select id="theme"><option>light</option><option>dark</option></select></label>
<label>Note <input id="note"></label>
<pre id="out"></pre>Preview
localStorage and sessionStorage: summary
Key points
- About 5 MB per origin, and access is synchronous, so keep the data small.
- Any script on the page can read it; never store tokens or personal data there.
- Access can throw in private mode or when storage is full; wrap it in
try/catch.
Frequently asked questions
›Does localStorage expire?
No. It stays until your code or the user clears it. Store a timestamp alongside the value if you need expiry.