HTML APIs
LocalStorage and SessionStorage Web Storage APIs
The HTML5 Web Storage API gives every web page a simple key-value store in the browser through two objects: localStorage, which persists indefinitely, and sessionStorage, which is cleared when the tab closes.
What is Web Storage and why use it?
Web Storage is an HTML5 API for storing string key-value pairs in the browser, scoped to a single origin (protocol + host + port). It replaced the old habit of stuffing small data into cookies. It comes in two flavours that share the same methods but differ in lifetime and scope: window.localStorage and window.sessionStorage.
Use it to remember a user's theme, cache API responses, save the state of a multi-step form, or keep a shopping cart on the client. It is fast, synchronous, and never sent to the server, which keeps requests small.
localStorage vs sessionStorage
localStorage keeps data until code or the user deletes it - it survives tab closes, browser restarts and reboots, and is shared across all tabs of the same origin. sessionStorage is isolated to a single tab and wiped the moment that tab or window closes.
| Feature | localStorage | sessionStorage |
|---|---|---|
| Lifetime | Until deleted (persistent) | Until the tab/window closes |
| Scope | Shared across all tabs of the origin | Only the tab that created it |
| Survives restart | Yes | No |
| Typical use | Preferences, theme, cached data | Multi-step form state, one-visit data |
Syntax: the four core methods
Both objects expose the same interface: setItem, getItem, removeItem and clear, plus the key(index) and length helpers to iterate stored items.
localStorage.setItem("theme", "dark"); // save
const theme = localStorage.getItem("theme"); // read -> "dark" (null if absent)
localStorage.removeItem("theme"); // delete one key
localStorage.clear(); // wipe everything for this origin
// iterate all keys
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
console.log(key, localStorage.getItem(key));
}
sessionStorage.setItem("step", "2"); // identical APIExample: a counter that remembers its value
Paste this page into the editor and click the buttons. In a normal browser tab the count survives a reload because it is read back from localStorage on load. Note the sandbox caveat below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Web Storage demo</title>
<style>
body { font-family: system-ui, sans-serif; padding: 24px; }
button { padding: 8px 16px; font-size: 15px; cursor: pointer; margin-right: 8px; }
#count { font-size: 28px; font-weight: bold; margin: 16px 0; }
</style>
</head>
<body>
<h3>Persistent counter</h3>
<div id="count">0</div>
<button id="inc">+1</button>
<button id="reset">Reset</button>
<script>
const el = document.getElementById("count");
function render() {
const saved = localStorage.getItem("count");
el.textContent = saved === null ? "0" : saved;
}
document.getElementById("inc").addEventListener("click", () => {
const next = Number(localStorage.getItem("count") || 0) + 1;
localStorage.setItem("count", String(next));
render();
});
document.getElementById("reset").addEventListener("click", () => {
localStorage.removeItem("count");
render();
});
render(); // restore the value when the page loads
</script>
</body>
</html>More examples: storing objects with JSON
Web Storage can only hold strings. To store objects or arrays, serialise them with JSON.stringify() when saving and JSON.parse() when reading. Anything non-string you pass is coerced to a string, which is why a raw object becomes the useless "[object Object]".
const user = { name: "Aditi", role: "intern", darkMode: true };
localStorage.setItem("user", JSON.stringify(user)); // save
const saved = JSON.parse(localStorage.getItem("user")); // load
console.log(saved.name); // "Aditi"
// guard against missing or corrupt data
let prefs;
try {
prefs = JSON.parse(localStorage.getItem("prefs")) || {};
} catch {
prefs = {};
}Web Storage vs Cookies
| Aspect | Web Storage | Cookies |
|---|---|---|
| Capacity | ~5 MB per origin | ~4 KB per cookie |
| Sent to server | No, stays in the browser | Yes, on every HTTP request |
| Expiry | localStorage never; session on tab close | Configurable via Expires / Max-Age |
| Access | JavaScript only | JavaScript + server (unless HttpOnly) |
| Best for | Client-side state and caching | Auth/session IDs, server-read data |
Capacity is roughly 5 MB per origin (some browsers allow up to 10 MB). Exceeding the quota throws a QuotaExceededError, so wrap large writes in try/catch. Data is stored as UTF-16, so each character can count as 2 bytes toward the limit.
Web Storage is synchronous and readable by any script on the page, so it is vulnerable to XSS - never store passwords, tokens or sensitive personal data in it. Also note the 'Try it' editor runs in a sandboxed iframe, which may restrict or reset storage between runs; the exact same code persists normally on a real page.
Listen for the 'storage' event on window to react when localStorage changes in another tab of the same origin - perfect for keeping tabs in sync, like logging out everywhere at once.
Key Takeaways
- localStorage persists forever; sessionStorage clears when the tab closes.
- The API is the same for both: setItem, getItem, removeItem, clear, key, length.
- Storage holds only strings - use JSON.stringify / JSON.parse for objects and arrays.
- Budget around 5 MB per origin and catch QuotaExceededError on big writes.
- Unlike cookies, Web Storage is never sent to the server - and must never hold secrets.
