Web Storage is a feature in HTML5 that lets web applications store data directly in the user’s browser.
It’s designed to store data locally (on the client side) in a simple key–value format.
Unlike cookies:
- Web Storage data is not sent automatically with every HTTP request.
- Much larger storage capacity (usually 5–10 MB vs ~4 KB for cookies).
- Easier and faster to use.
🛠️ Types of Web Storage
There are two types of Web Storage:
1. localStorage
- Stores data permanently in the browser (until manually deleted).
- Survives page reloads and browser restarts.
- Capacity: ~5–10 MB depending on browser.
2. sessionStorage
- Stores data temporarily for the current browser tab/session.
- Data is lost when the tab or browser is closed.
- Capacity: similar to localStorage (~5 MB).
📝 Example: localStorage
<!DOCTYPE html>
<html>
<head>
<title>localStorage Example</title>
</head>
<body>
<h2>localStorage Demo</h2>
<button onclick="saveData()">Save Data</button>
<button onclick="getData()">Get Data</button>
<button onclick="removeData()">Remove Data</button>
<script>
function saveData() {
localStorage.setItem("username", "JohnDoe");
alert("Data saved!");
}
function getData() {
const user = localStorage.getItem("username");
alert("Stored username: " + user);
}
function removeData() {
localStorage.removeItem("username");
alert("Data removed!");
}
</script>
</body>
</html>
📝 Example: sessionStorage
<script>
// Save to sessionStorage
sessionStorage.setItem("sessionUser", "Alice");
// Retrieve
console.log(sessionStorage.getItem("sessionUser")); // Alice
// Remove
sessionStorage.removeItem("sessionUser");
// Clear all session data
sessionStorage.clear();
</script>
✅ Key Differences: localStorage vs sessionStorage
| Feature | localStorage | sessionStorage |
|---|---|---|
| Persistence | Permanent (until cleared) | Temporary (ends with tab/close) |
| Scope | Shared across tabs of same site | Per tab/session only |
| Capacity | ~5–10 MB | ~5–10 MB |
🔑 When to Use
- localStorage: Save user preferences, theme settings, authentication tokens, cached data.
- sessionStorage: Temporary data like form inputs, shopping cart (until checkout), or per-session state.
⚠️ Limitations
- Can only store strings (objects must be converted to JSON).
- Not secure for sensitive data (like passwords, tokens) → better to use
HttpOnlycookies or secure storage.