Lesson 32 of 55 · HTML
Web Storage – localStorage & sessionStorage
Duration: 9 min
Storing Data on the Client
Both APIs provide a simple key‑value store (strings only).
// Save a value
localStorage.setItem('theme', 'dark');
// Retrieve
const theme = localStorage.getItem('theme');
// Session‑only data
sessionStorage.setItem('temp', '123');
Differences
localStorage– Persists across sessions until cleared; shared across all tabs/windows of the same origin.sessionStorage– Clears when the tab/window closes; scoped to a single browsing context.
Usage tips
- Use JSON for structured data:
localStorage.setItem('profile', JSON.stringify(obj));. - Listen to the
storageevent to sync changes across tabs:
window.addEventListener('storage', e => {
if (e.key === 'theme') { applyTheme(e.newValue); }
});
- Respect storage limits (~5 MB) and never store sensitive data in plain text.
- When storing large objects, consider compression (e.g., LZString) before saving.
Quick checklist for Web Storage
- Data stored as strings (use
JSON.stringifyfor objects)? ✅ - Sensitive info avoided (no passwords, tokens)? ✅
storageevent used for cross‑tab sync where needed? ✅- Storage size monitored (avoid exceeding ~5 MB)? ✅
- Fallback strategy for browsers without Storage (e.g., cookies) implemented? ✅
Tip: Use localStorage for UI preferences (theme, language) and sessionStorage for temporary form state that shouldn’t survive a page reload.