JavaScript developers, take heed! localStorage has served us well, but modern web applications demand more: larger storage limits, structured data, asynchronous operations, and quota awareness. The web platform now offers a richer set of storage APIs that address these needs.
The Limits of localStorage:
localStorage is synchronous, limited to roughly 5MB per origin, stores only strings, and blocks the main thread on every read and write. For small key-value pairs it's fine, but for caching API responses, storing user-generated content, or handling offline-first apps, it falls short.
Link to section: 1. IndexedDB for Structured, Asynchronous Storage1. IndexedDB for Structured, Asynchronous Storage
IndexedDB is a NoSQL database in the browser. It stores objects, handles large datasets, and operates asynchronously:
// Open a database
const request = indexedDB.open('myDatabase', 1);
request.onupgradeneeded = (event) => {
const db = event.target.result;
// Create an object store (like a table)
if (!db.objectStoreNames.contains('posts')) {
db.createObjectStore('posts', { keyPath: 'id' });
}
};
request.onsuccess = (event) => {
const db = event.target.result;
// Add a record
const tx = db.transaction('posts', 'readwrite');
const store = tx.objectStore('posts');
store.add({ id: 1, title: 'Hello', body: 'World' });
tx.oncomplete = () => console.log('Saved!');
};
Link to section: 2. The idb-keyval Library for Simplicity2. The idb-keyval Library for Simplicity
Raw IndexedDB is verbose. The idb-keyval library wraps it in a promise-based API that feels like localStorage:
import { get, set, del } from 'idb-keyval';
// Set a value (async, non-blocking)
await set('user-preferences', { theme: 'dark', lang: 'en' });
// Get a value
const prefs = await get('user-preferences');
console.log(prefs); // { theme: 'dark', lang: 'en' }
// Delete a value
await del('user-preferences');
Link to section: 3. The Storage API for Quota Management3. The Storage API for Quota Management
The Storage API lets you check and request persistent storage, preventing the browser from evicting your data under pressure:
// Check available quota
if (navigator.storage && navigator.storage.estimate) {
const { usage, quota } = await navigator.storage.estimate();
console.log(`Using ${usage} bytes out of ${quota} bytes`);
console.log(`${((usage / quota) * 100).toFixed(2)}% of quota used`);
}
// Request persistent storage to avoid eviction
if (navigator.storage && navigator.storage.persist) {
const isPersisted = await navigator.storage.persist();
console.log(`Storage persisted: ${isPersisted}`);
}
Link to section: 4. The Cache API for Network Responses4. The Cache API for Network Responses
The Cache API, designed for Service Workers, is excellent for storing Response objects and building offline-first experiences:
// Cache a fetch response
const cache = await caches.open('api-cache-v1');
await cache.add('/api/posts');
// Or cache manually
const response = await fetch('/api/posts');
await cache.put('/api/posts', response.clone());
// Retrieve from cache
const cachedResponse = await cache.match('/api/posts');
if (cachedResponse) {
const data = await cachedResponse.json();
console.log('From cache:', data);
}
Link to section: 5. Session Storage for Tab-Scoped State5. Session Storage for Tab-Scoped State
sessionStorage behaves like localStorage but clears when the tab closes, ideal for temporary state like form drafts or wizard steps:
// Save a form draft
sessionStorage.setItem('form-draft', JSON.stringify(formData));
// Restore on reload
const draft = JSON.parse(sessionStorage.getItem('form-draft') || 'null');
Link to section: Choosing the Right ToolChoosing the Right Tool
| Need | API |
|---|---|
| Small key-value, synchronous | localStorage |
| Tab-scoped temporary state | sessionStorage |
| Large or structured data | IndexedDB / idb-keyval |
| Caching network responses | Cache API |
| Quota and persistence control | Storage API |
Embrace a New Era of Web Storage:
The modern web storage landscape offers the right tool for every job. By moving beyond localStorage to IndexedDB, the Cache API, and the Storage API, you can build faster, more resilient applications that handle data gracefully at any scale.
MDN Web Docs: Storage API
Start exploring these modern storage patterns and level up your offline-first and data-heavy applications!