What is the difference between localStorage, sessionStorage, and cookies?
All three store data in the browser, but differ in size, lifetime, and whether they're sent to the server.
localStorage — persists until cleared, ~5–10 MB, never sent to the server. Best for long-lived client data.
sessionStorage — cleared when the tab closes, ~5 MB, scoped to one tab. Best for temporary per-session data.
Cookies — small (~4 KB), can expire, and are sent with every HTTP request. Best for server-read data like auth tokens.
Security tip: auth cookies should be HttpOnly and Secure so JavaScript can't read them.
// localStorage - persists forever
localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme'); // 'dark'
localStorage.removeItem('theme');
localStorage.clear(); // Remove all
// sessionStorage - per tab, per session
sessionStorage.setItem('formDraft', JSON.stringify(formData));
const draft = JSON.parse(sessionStorage.getItem('formDraft'));
// Cookies
document.cookie = 'user=John; max-age=86400; path=/; SameSite=Lax';
// Reading cookies (messy)
function getCookie(name) {
const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
return match ? match[2] : null;
}
// For auth - set by server with HttpOnly (JS cannot access)
// Set-Cookie: token=abc123; HttpOnly; Secure; SameSite=Strict
// Storage events (sync across tabs)
window.addEventListener('storage', (event) => {
console.log(`${event.key}: ${event.oldValue} → ${event.newValue}`);
// Only fires in OTHER tabs (not the one that made the change)
});localStorage has a simple key-value API that persists forever. sessionStorage has the same API but clears on tab close. Cookies use a string format and are sent with every HTTP request.
HttpOnly cookies cannot be read by JavaScript (security). The storage event syncs changes across tabs (useful for logout sync).
Know capacity (5-10MB vs 4KB), lifetime (permanent vs session vs configurable), and server transmission (storage: no, cookies: yes). HttpOnly cookies for auth tokens (XSS-safe) is the key security point.
The storage event for cross-tab sync is a bonus detail.