HTML APIs
LocalStorage and SessionStorage Web Storage APIs
The Web Storage API gives web pages a simple key-value store in the browser through two objects: localStorage (persists indefinitely) and sessionStorage (cleared when the tab closes).
What is Web Storage?
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.
localStorage vs sessionStorage
localStorage keeps data until the code (or the user) explicitly 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 is wiped the moment that tab or window is closed.
| 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 | User preferences, theme, cached data | Multi-step form state, one-visit data |
The four core methods
Both objects expose the same interface: setItem, getItem, removeItem, clear, plus the key(index) and length helpers to iterate stored items.
// Save a value
localStorage.setItem("theme", "dark");
// Read it back (returns null if the key does not exist)
const theme = localStorage.getItem("theme"); // "dark"
// Remove a single key
localStorage.removeItem("theme");
// Wipe everything for this origin
localStorage.clear();
// Iterate all keys
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
console.log(key, localStorage.getItem(key));
}
// sessionStorage uses the exact same API
sessionStorage.setItem("step", "2");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 silently coerced to a string, which is why raw objects become the useless "[object Object]".
const user = { name: "Aditi", role: "intern", darkMode: true };
// Save: serialise to a JSON string
localStorage.setItem("user", JSON.stringify(user));
// Load: parse back into an object
const saved = JSON.parse(localStorage.getItem("user"));
console.log(saved.name); // "Aditi"
// Guard against missing / corrupt data
let prefs;
try {
prefs = JSON.parse(localStorage.getItem("prefs")) || {};
} catch {
prefs = {};
}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. Never store passwords, tokens or sensitive personal data in it - it is vulnerable to XSS. Also note it is not sent to the server automatically, unlike cookies.
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; sessionStorage on tab close | Configurable via Expires/Max-Age |
| Access | JavaScript only | JavaScript + server (unless HttpOnly) |
| Best for | Client-side state and caching | Auth/session identifiers, server-read data |
Listen for the 'storage' event on window to react when localStorage changes in another tab of the same origin - useful for keeping multiple tabs in sync (e.g. logging out everywhere at once).
