What is the difference between sessionStorage and localStorage?
Both are Web Storage with the same simple key–value API, differing in lifetime and scope.
localStorage — persists until explicitly cleared, and is shared across all tabs of the same origin.
sessionStorage — lasts only for the tab's session and is isolated to that single tab.
Both store strings only and are synchronous — serialise objects with JSON, and keep data small.
// localStorage — persists forever
localStorage.setItem('theme', 'dark');
console.log(localStorage.getItem('theme')); // 'dark'
// Still there after closing browser!
// sessionStorage — per tab, cleared on close
sessionStorage.setItem('formDraft', JSON.stringify({ name: 'John' }));
const draft = JSON.parse(sessionStorage.getItem('formDraft'));
// Gone when tab is closed!
// Storing objects (must serialize)
const user = { name: 'John', age: 30 };
localStorage.setItem('user', JSON.stringify(user));
const stored = JSON.parse(localStorage.getItem('user'));
// Listen for changes across tabs (localStorage only)
window.addEventListener('storage', (e) => {
console.log(`${e.key}: ${e.oldValue} → ${e.newValue}`);
});localStorage persists forever and is shared across tabs. sessionStorage is per-tab and cleared on close. Both store strings only — JSON.stringify for objects.
The storage event fires in OTHER tabs when localStorage changes (useful for logout sync). sessionStorage does NOT trigger storage events in other tabs.
localStorage = permanent + shared across tabs. sessionStorage = per-tab + cleared on close. Both store strings only (JSON.stringify for objects).
The storage event for cross-tab sync (logout all tabs) is the advanced detail. Neither is sent to the server (unlike cookies).