Web Storage API
Browsers ship two key-value stores: localStorage (persists across sessions) and sessionStorage (cleared on tab close). Both store strings only.
The four operations
JS
localStorage.setItem("theme", "dark");
localStorage.getItem("theme"); // "dark"
localStorage.removeItem("theme");
localStorage.clear();
// Same API on sessionStorage
Store objects — serialise
JS
localStorage.setItem("user", JSON.stringify({ name: "Ada", role: "admin" }));
const user = JSON.parse(localStorage.getItem("user") ?? "null");
// Always handle null + bad JSON if data may not exist or got corrupted
localStorage vs. sessionStorage vs. cookies
| localStorage | sessionStorage | Cookies | |
|---|---|---|---|
| Lifetime | Until cleared | Until tab closes | Custom (max-age) |
| Capacity | ~5–10 MB | ~5–10 MB | ~4 KB |
| Sent to server | No | No | Every request |
| API | Synchronous | Synchronous | String parsing |
React to changes in other tabs
JS
window.addEventListener("storage", (e) => {
// e.key, e.oldValue, e.newValue — fired in OTHER tabs only
if (e.key === "theme") applyTheme(e.newValue);
});
When to reach for IndexedDB instead
- You need more than 5 MB.
- You want async / non-blocking access.
- You're storing structured data and want to query it.
- You need transactions.
Security: Never store auth tokens in localStorage. Any JS on the page (including a compromised dependency) can read them. Use HttpOnly cookies set by the server.
Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from Web Storage API!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Save a string value across sessions.
localStorage.
('theme', 'dark');
Two words concatenated.
Discussion
Loading…