Web Storage in JavaScript
Modern web applications frequently need to store data on the client side to improve performance, enable offline capabilities, or maintain user sessions. Browsers provide several mechanisms for client-side storage, each with unique characteristics and use cases.
1. LocalStorage
localStorage provides persistent storage for key-value pairs. Data stored in localStorage has no expiration time; it persists even after the browser is closed and reopened.
- Capacity: Typically ~5MB to 10MB per origin.
- Data Type: Only strings. Objects must be serialized using
JSON.stringify(). - Accessibility: Accessible across all tabs and windows sharing the same origin (protocol, domain, port).
- Synchronous: Operations block the main thread.
// Saving data
localStorage.setItem('theme', 'dark');
localStorage.setItem('user', JSON.stringify({ id: 1, name: 'Alice' }));
// Reading data
const theme = localStorage.getItem('theme');
const user = JSON.parse(localStorage.getItem('user'));
// Removing data
localStorage.removeItem('theme');
localStorage.clear(); // Clears all data for the origin
2. SessionStorage
sessionStorage is identical to localStorage in API and synchronous nature, but with a fundamentally different lifecycle. Data in sessionStorage is cleared when the page session ends (i.e., when the specific browser tab is closed).
- Capacity: Typically ~5MB per origin.
- Data Type: Only strings.
- Accessibility: Isolated to the specific tab. Opening a new tab with the same URL creates a new session. Survives page reloads within the same tab.
// Perfect for temporary state, like form data on a multi-step form
sessionStorage.setItem('currentStep', '2');
3. Cookies
Cookies are small text strings primarily used for session management, personalization, and tracking. While they can store data, their unique trait is that they are automatically sent to the server with every HTTP request.
- Capacity: ~4KB per cookie.
- Expiration: Can be set manually. If not set, they act as session cookies and expire when the browser is closed.
- Security: Can be marked as
HttpOnly(inaccessible via JavaScript, mitigating XSS) andSecure(sent only over HTTPS).
// Setting a cookie with an expiration date
document.cookie = "username=JohnDoe; expires=Thu, 18 Dec 2025 12:00:00 UTC; path=/";
Note: Due to their impact on network payload size, cookies should not be used for general client-side data storage.
4. IndexedDB
IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files and blobs. It is a full-fledged NoSQL transactional database built into the browser.
- Capacity: Depends on the browser and disk space, but generally vast (hundreds of MBs to GBs).
- Data Type: Can store complex structured data (objects, Blobs, Files, ArrayBuffers).
- Asynchronous: Uses an event-driven, asynchronous API, ensuring it doesn't block the main thread.
- Use Cases: Progressive Web Apps (PWAs), offline capabilities, caching large datasets, offline games.
// IndexedDB APIs are complex. Here is a conceptual overview:
const request = indexedDB.open('MyDatabase', 1);
request.onupgradeneeded = (event) => {
const db = event.target.result;
const objectStore = db.createObjectStore('users', { keyPath: 'id' });
objectStore.createIndex('name', 'name', { unique: false });
};
request.onsuccess = (event) => {
const db = event.target.result;
// Transactions are required for reading/writing
const transaction = db.transaction(['users'], 'readwrite');
const store = transaction.objectStore('users');
store.add({ id: 1, name: 'Alice', role: 'admin' });
};
Summary Comparison
| Feature | LocalStorage | SessionStorage | Cookies | IndexedDB | | :--- | :--- | :--- | :--- | :--- | | Capacity | ~5-10MB | ~5MB | ~4KB | Uncapped (GBs) | | Lifespan | Persistent | Until tab closes | Persistent/Session | Persistent | | Data Types | Strings | Strings | Strings | Complex Objects, Blobs | | Execution | Synchronous | Synchronous | Synchronous | Asynchronous | | Sent w/ HTTP | No | No | Yes | No | | Primary Use | App settings, tokens | Temporary UI state | Session IDs, Auth | Large data, PWAs, Offline |