Web Storage API
Store data locally in the user's browser with localStorage and sessionStorage. Build offline-capable applications with persistent and session-based storage.
What is the difference between localStorage and sessionStorage?
Both store string key/value pairs in the browser, about 5 MB per origin, through setItem, getItem and removeItem. localStorage persists until it's cleared, even after the browser closes. sessionStorage lasts only for the current tab and is cleared when the tab closes. Store objects with JSON.stringify and read them back with JSON.parse.
localStorage.setItem("theme", "dark");
localStorage.getItem("theme"); // "dark"
const cart = { items: [1, 2] };
localStorage.setItem("cart", JSON.stringify(cart));
JSON.parse(localStorage.getItem("cart"));
sessionStorage.setItem("step", "2");Storage Types
LocalStorage
- Persists until manually cleared
- Shared across browser tabs
- ~5-10MB storage limit
SessionStorage
- Cleared when tab closes
- Tab-specific storage
- Same storage capacity
Interactive Storage Examples
Explore both localStorage and sessionStorage with interactive examples including JSON storage, quota checking, and storage events.
localStorage vs sessionStorage
localStorage
- Persistence: Data survives browser restart
- Scope: Shared across all tabs/windows
- Lifetime: Until explicitly cleared
- Capacity: ~5-10MB per origin
- Use Cases: User preferences, shopping carts
sessionStorage
- Persistence: Cleared when tab closes
- Scope: Isolated per tab/window
- Lifetime: Duration of page session
- Capacity: ~5-10MB per origin
- Use Cases: Form data, temporary state
Web Storage API Methods
Core Methods
setItem(key, value)Store a key-value pair
getItem(key)Retrieve value by key
removeItem(key)Remove specific item
clear()Remove all items
Properties & Iteration
lengthNumber of stored items
key(index)Get key at specific index
Object.keys(storage)Get all keys as array
for...in loopIterate through all items
Advanced Storage Techniques
JSON Object Storage
Storing Objects
const user = { name: 'John', age: 30 };
localStorage.setItem('user', JSON.stringify(user));Retrieving Objects
const userStr = localStorage.getItem('user');
const user = JSON.parse(userStr || '{}');Storage Wrapper Pattern
Create a wrapper class for safer storage operations:
class StorageManager {
static set(key, value, isSession = false) {
try {
const storage = isSession ? sessionStorage : localStorage;
storage.setItem(key, JSON.stringify(value));
return true;
} catch (error) {
console.error('Storage error:', error);
return false;
}
}
static get(key, isSession = false) {
try {
const storage = isSession ? sessionStorage : localStorage;
const item = storage.getItem(key);
return item ? JSON.parse(item) : null;
} catch (error) {
console.error('Storage error:', error);
return null;
}
}
}Storage Events & Synchronization
Event Properties
key- The changed keyoldValue- Previous valuenewValue- New valueurl- Page that triggered changestorageArea- localStorage/sessionStorage
Cross-Tab Communication
window.addEventListener('storage', (e) => {
if (e.key === 'user-status') {
updateUserInterface(e.newValue);
}
});Limitations & Best Practices
Storage Limitations
- • 5-10MB storage quota per origin
- • Strings only (no binary data)
- • Synchronous API (can block UI)
- • No automatic expiration
- • Subject to user clearing data
Security Considerations
- • Never store sensitive data
- • Validate data before storing
- • Consider XSS attack vectors
- • Use HTTPS for secure contexts
- • Implement data encryption if needed
Performance Best Practices
- • Always use try-catch blocks
- • Check storage availability first
- • Minimize large data operations
- • Use efficient data structures
- • Implement graceful fallbacks
Data Management
- • Implement data versioning
- • Use consistent naming conventions
- • Regular cleanup of old data
- • Monitor storage usage
- • Provide user data controls
Real-World Use Cases & Examples
User Preferences & Settings
- • Theme preferences (dark/light mode)
- • Language and localization settings
- • UI layout configurations
- • Notification preferences
- • Accessibility settings
Application State
- • Shopping cart contents
- • Form data persistence
- • User progress in applications
- • Recently viewed items
- • Search history and filters
Performance Optimization
- • API response caching
- • Static resource versioning
- • Offline functionality support
- • Reduced server requests
- • Background data prefetching
Analytics & Tracking
- • User behavior patterns
- • Feature usage statistics
- • A/B testing configurations
- • Error logging and reporting
- • Performance metrics storage
Code Editor
<label>Your name <input id="name"></label>
<button id="save">Save</button>
<button id="clear">Clear</button>
<p id="out"></p>Preview
Web Storage — step by step
Understand localStorage vs sessionStorage
localStorage persists data indefinitely until explicitly cleared, even across browser restarts. sessionStorage is scoped to the current tab and is cleared when the tab is closed. Both are synchronous and store strings only.
🎯 Quick Check
Which Web Storage type clears automatically when the browser tab is closed?
Web Storage (localStorage): summary
Key points
- Storage is synchronous and blocks the main thread; keep the data small.
- Never store tokens or secrets there: any script on the page, including injected ones, can read it.
- Wrap access in
try/catch, because private browsing or full storage can throw errors. - Use IndexedDB for large or structured data.
Frequently asked questions
›How much data can localStorage hold?
Usually about 5 MB per origin, depending on the browser.
›Is localStorage secure?
It isn't encrypted and is readable by any JavaScript on your origin. Don't store authentication tokens or personal data in it.