HTML Web Storage
Learn how to store data in the browser using localStorage and sessionStorage
The HTML Web Storage API provides two mechanisms for storing data
on the client side: localStorage
for persistent
storage and sessionStorage
for session-based storage.
Both allow you to store data without using cookies.
What is Web Storage?
Web Storage provides a way to store key-value pairs in the browser. It's more secure and faster than cookies, and can store larger amounts of data (typically 5-10 MB per origin).
Key Benefits
- More Storage: 5-10 MB vs 4 KB for cookies
- Never Sent to Server: Reduces bandwidth usage
- Simple API: Easy to use key-value interface
- Synchronous: No callbacks needed
localStorage vs sessionStorage
HTML Web Storage provides two storage objects with different lifetimes:
Checking for Storage Support
Always check if Web Storage is supported before using it:
Feature Detection
if (typeof(Storage) !== "undefined") {
// Web Storage is supported
console.log("localStorage is available");
} else {
// Web Storage is not supported
console.log("Sorry, Web Storage is not supported");
}
Web Storage Methods
Both localStorage and sessionStorage have the same methods and properties:
localStorage Examples
Basic localStorage Operations
// Store data
localStorage.setItem("username", "John Doe");
localStorage.setItem("email", "john@example.com");
// Retrieve data
var username = localStorage.getItem("username");
console.log(username); // "John Doe"
// Remove specific item
localStorage.removeItem("email");
// Clear all data
localStorage.clear();
// Check number of items
console.log(localStorage.length);
Storing Objects (JSON)
// Store object
var user = {
name: "John Doe",
age: 30,
email: "john@example.com"
};
// Convert to JSON string before storing
localStorage.setItem("user", JSON.stringify(user));
// Retrieve and parse
var storedUser = JSON.parse(localStorage.getItem("user"));
console.log(storedUser.name); // "John Doe"
💡 Important
Web Storage can only store strings. Use
JSON.stringify()
to store objects and
JSON.parse()
to retrieve them.
sessionStorage Examples
Using sessionStorage
// Store temporary data
sessionStorage.setItem("cartItems", "3");
sessionStorage.setItem("currentPage", "checkout");
// Retrieve data
var items = sessionStorage.getItem("cartItems");
console.log(items); // "3"
// Data persists during page reload
location.reload(); // cartItems still available
// Data is cleared when tab closes
// (Open in new tab - data won't be there)
Form State Preservation
<form id="myForm">
<input type="text" id="name" placeholder="Name">
<input type="email" id="email" placeholder="Email">
<button type="submit">Submit</button>
</form>
<script>
// Save form data on input
document.getElementById("name").addEventListener("input", function(e) {
sessionStorage.setItem("formName", e.target.value);
});
document.getElementById("email").addEventListener("input", function(e) {
sessionStorage.setItem("formEmail", e.target.value);
});
// Restore form data on page load
window.addEventListener("load", function() {
var name = sessionStorage.getItem("formName");
var email = sessionStorage.getItem("formEmail");
if (name) document.getElementById("name").value = name;
if (email) document.getElementById("email").value = email;
});
// Clear data on submit
document.getElementById("myForm").addEventListener("submit", function() {
sessionStorage.removeItem("formName");
sessionStorage.removeItem("formEmail");
});
</script>
Practical Examples
Dark Mode Toggle
<button onclick="toggleDarkMode()">Toggle Dark Mode</button>
<script>
// Check saved preference on load
window.addEventListener("load", function() {
var darkMode = localStorage.getItem("darkMode");
if (darkMode === "enabled") {
document.body.classList.add("dark-mode");
}
});
function toggleDarkMode() {
document.body.classList.toggle("dark-mode");
// Save preference
if (document.body.classList.contains("dark-mode")) {
localStorage.setItem("darkMode", "enabled");
} else {
localStorage.setItem("darkMode", "disabled");
}
}
</script>
Visit Counter
<p>You have visited this page <span id="count">0</span> times.</p>
<script>
// Get current count or initialize to 0
var count = localStorage.getItem("visitCount") || 0;
// Increment count
count++;
// Store new count
localStorage.setItem("visitCount", count);
// Display count
document.getElementById("count").textContent = count;
</script>
Shopping Cart
// Shopping cart manager
var cart = {
add: function(item) {
var items = this.getItems();
items.push(item);
localStorage.setItem("cart", JSON.stringify(items));
},
remove: function(itemId) {
var items = this.getItems();
items = items.filter(function(item) {
return item.id !== itemId;
});
localStorage.setItem("cart", JSON.stringify(items));
},
getItems: function() {
var items = localStorage.getItem("cart");
return items ? JSON.parse(items) : [];
},
clear: function() {
localStorage.removeItem("cart");
},
getTotal: function() {
var items = this.getItems();
return items.reduce(function(total, item) {
return total + item.price;
}, 0);
}
};
// Usage
cart.add({ id: 1, name: "Product 1", price: 29.99 });
cart.add({ id: 2, name: "Product 2", price: 49.99 });
console.log(cart.getItems());
console.log("Total: $" + cart.getTotal());
Storage Events
The storage event fires when a storage area changes (in another window/tab):
Listening for Storage Changes
window.addEventListener("storage", function(e) {
console.log("Storage changed!");
console.log("Key: " + e.key);
console.log("Old value: " + e.oldValue);
console.log("New value: " + e.newValue);
console.log("URL: " + e.url);
console.log("Storage area: ", e.storageArea);
});
// This event only fires in OTHER windows/tabs
// Changes in the same window don't trigger it
⚠️ Note
The storage event only fires in other windows/tabs with the same origin. It does NOT fire in the window that made the change.
Web Storage Best Practices
Best Practices
- Check for Support: Always verify Web Storage is available
- Handle Errors: Wrap storage operations in try-catch blocks
- Don't Store Sensitive Data: Never store passwords or tokens
- Use JSON for Objects: Convert objects to strings with JSON.stringify()
- Set Expiration: Implement your own expiration mechanism
- Validate Data: Always validate retrieved data
- Monitor Storage Size: Be aware of storage limits (5-10 MB)
- Clean Up: Remove unused data regularly
- Use Appropriate Storage: Choose localStorage vs sessionStorage wisely
- Namespace Keys: Use prefixes to avoid key collisions
Error Handling Example
function safeSetItem(key, value) {
try {
localStorage.setItem(key, value);
return true;
} catch (e) {
if (e.name === 'QuotaExceededError') {
console.error('Storage quota exceeded');
} else {
console.error('Error saving to localStorage:', e);
}
return false;
}
}
function safeGetItem(key, defaultValue) {
try {
var value = localStorage.getItem(key);
return value !== null ? value : defaultValue;
} catch (e) {
console.error('Error reading from localStorage:', e);
return defaultValue;
}
}
🔒 Security Notes
- Web Storage is accessible via JavaScript - vulnerable to XSS attacks
- Data is stored unencrypted in plain text
- Never store sensitive information like passwords or credit cards
- Data persists across sessions (localStorage) - consider privacy implications