Web Storage: localStorage & sessionStorage
Client-side storage APIs, code examples, and how they compare with cookies and IndexedDB.
The Web Storage API
Before HTML5, cookies (~4 KB) were the only client-side storage option — limited, insecure, and sent with every request.
| localStorage | sessionStorage |
|---|---|
|
Persistent — survives browser close/reopen Scoped per origin (domain + protocol + port) ~5 MB per origin (browser-dependent) JavaScript key-value API: setItem / getItemNOT sent to server — stays in the browser Use for preferences, cached data, offline content |
Session-scoped — cleared when the tab/window closes Each tab has its own independent storage Same ~5 MB size limit Identical API to localStorage Use for per-session state: forms, wizard steps More private — not shared between tabs |
Web Storage — Code Examples
// localStorage
if (typeof Storage !== "undefined") {
// Store a string value
localStorage.setItem("username", "Alice");
// Store an object (serialize to JSON)
const prefs = { theme: "dark", lang: "en" };
localStorage.setItem("prefs", JSON.stringify(prefs));
// Retrieve and parse
const saved = JSON.parse(localStorage.getItem("prefs"));
console.log(saved.theme); // "dark"
// Remove one key / clear everything
localStorage.removeItem("username");
localStorage.clear();
}
// sessionStorage
sessionStorage.setItem("step", "2");
const step = sessionStorage.getItem("step"); // "2"
// Iterate all keys
for (let i = 0; i < sessionStorage.length; i++) {
const key = sessionStorage.key(i);
console.log(key, sessionStorage.getItem(key));
}
Storage Options Comparison
| Size limit | Sent to server | Data types | Best for | |
|---|---|---|---|---|
| Cookie | ~4 KB | Yes (every request) | Strings only | Auth tokens |
| localStorage | ~5 MB+ | No | Strings only | Preferences / cache |
| sessionStorage | ~5 MB+ | No | Strings only | Per-session state |
| IndexedDB | Hundreds of MB+ | No | Any JS object | Large / complex data |
Activity — complete the code
Complete the code correctly to mark this lesson as complete automatically.
Complete the Web Storage code.
// Save a valuelocalStorage.("username", "Alice");// Read a valueconst name = localStorage.("username");// sessionStorage is cleared when the closes.