Web Storage (or DOM Storage) is an HTML5 API that provides JavaScript methods to store key/value pairs of data locally within the user’s browser. This data can persist across page loads and even browser sessions.
1. Web Storage vs. Cookies
| Feature | Web Storage (Local/Session) | Cookies (Old Method) |
| Storage Capacity | Much larger (typically 5MB to 10MB per domain). | Very small (limited to 4KB per domain). |
| Server Interaction | Data is never automatically sent to the server with every HTTP request. | Data is automatically sent to the server with every HTTP request. |
| Use Case | Client-side application data, caching user settings, storing offline data. | Session management, tracking, small personalized settings. |
2. Local Storage (localStorage)
localStorage is a property that allows you to store data with no expiration time. The data remains in the user’s browser until the user explicitly clears it, the application removes it, or the browser is manually reset.
- Persistence: Data persists even when the browser window is closed and reopened.
- Scope: The data is tied to the domain (origin).
Local Storage Methods (JavaScript)
| Method | Purpose |
setItem(key, value) | Stores a key/value pair. Both key and value must be strings. |
getItem(key) | Retrieves the value associated with the key. Returns null if the key doesn’t exist. |
removeItem(key) | Removes the key/value pair specified by the key. |
clear() | Removes all key/value pairs stored for that domain. |
// Store a setting
localStorage.setItem('theme', 'dark-mode');
// Retrieve a setting
const userTheme = localStorage.getItem('theme'); // 'dark-mode'
// Remove the key
localStorage.removeItem('theme');
Note: Since
localStorageonly stores strings, you must useJSON.stringify()to store objects or arrays andJSON.parse()to retrieve them.
3. Session Storage (sessionStorage)
sessionStorage works identically to localStorage in terms of methods (setItem, getItem, etc.), but the data is only available for the duration of the current session.
- Persistence: The data is cleared when the user closes the browser tab or window.
- Scope: Data is tied to the origin (domain) and the specific browser tab (session). If the user opens the same site in two different tabs, they will have two separate
sessionStorageinstances.
// Store a temporary state, like cart contents
sessionStorage.setItem('cart-count', '3');
// Retrieve it later in the same session
const cartCount = sessionStorage.getItem('cart-count'); // '3'
4. Security Considerations
Web Storage data is client-side only and is easily viewable and editable by the user using the browser’s Developer Tools.
- Never Store: Sensitive information like user passwords, credit card numbers, or authentication tokens that are not securely encrypted should never be stored in
localStorageorsessionStorage. - Use for: Non-sensitive data like UI preferences, reading progress, or temporary form data.
