Web Storage, Cookies and IndexedDB: Saving Data in the Browser
Persist data on the client: localStorage and sessionStorage, the storage event, JSON wrappers, cookies and their attributes (max-age, path, domain, Secure, HttpOnly, SameSite), the Cookie Store API, IndexedDB databases, transactions, indexes and cursors, quotas and eviction.
kvi5hnuCode Sprout team member9 min readOn this page
Web apps often need to remember things on the user's device: preferences, a draft message, a shopping cart, or a full offline copy of the user's data. Browsers provide several storage mechanisms with very different sizes, lifetimes and APIs. All of them are scoped to an origin (protocol, host and port), so one site can never read another site's data, and all of them are under the user's control: they can be cleared at any time, so never treat client storage as the only copy of important data.

Web Storage: localStorage and sessionStorage
localStorage and sessionStorage are simple key/value stores of strings:
localStorage.setItem("theme", "dark");
localStorage.getItem("theme"); // "dark"
localStorage.getItem("missing"); // null
localStorage.removeItem("theme");
localStorage.clear(); // remove everything for this origin
localStorage.length; // number of keys; localStorage.key(i) gets the i-th name
Property syntax (localStorage.theme = "dark", delete localStorage.theme) also works, but the methods avoid clashes with built-in names like length and key.
The two objects differ in lifetime and scope:
- localStorage persists until the site or the user deletes it, and is shared by all tabs and windows of the same origin (in the same browser profile).
- sessionStorage lasts as long as the tab: it survives reloads and restores, but each tab has its own separate copy, even for the same page.
Everything is a string
Values are converted to strings when stored, which causes classic bugs, as the stand-in below shows (it has the same methods as the real thing, so the example can run outside a browser). Store structured data as JSON, through a small wrapper that also guards against corrupted values:
// A small stand-in with the same methods as localStorage, so this runs anywhere
class MemoryStorage {
#data = new Map();
getItem(key) { return this.#data.has(key) ? this.#data.get(key) : null; }
setItem(key, value) { this.#data.set(key, String(value)); } // everything becomes a string
removeItem(key) { this.#data.delete(key); }
get length() { return this.#data.size; }
}
function createStore(storage, prefix) {
return {
get(key, fallback) {
const raw = storage.getItem(`${prefix}:${key}`);
if (raw === null) return fallback;
try {
return JSON.parse(raw);
} catch {
return fallback; // corrupted or hand-edited value
}
},
set(key, value) {
storage.setItem(`${prefix}:${key}`, JSON.stringify(value));
},
remove(key) {
storage.removeItem(`${prefix}:${key}`);
},
};
}
const storage = new MemoryStorage();
storage.setItem("visits", 3);
console.log(typeof storage.getItem("visits"), storage.getItem("visits") + 1); // a string!
const settings = createStore(storage, "app");
settings.set("prefs", { theme: "dark", fontSize: 18, tags: ["green"] });
console.log(settings.get("prefs"));
console.log(settings.get("missing", { theme: "light" }));
storage.setItem("app:broken", "{not json");
console.log(settings.get("broken", "default"));
settings.set("since", new Date(Date.UTC(2026, 0, 1)));
console.log(typeof settings.get("since")); // JSON turns Dates into strings
string 31
{ theme: 'dark', fontSize: 18, tags: [ 'green' ] }
{ theme: 'light' }
default
string
"3" + 1 is "31", a reminder to convert numbers when reading. JSON also loses types: Dates come back as strings, and Maps and class instances don't survive.
Other limits to keep in mind:
- The API is synchronous: reading or writing blocks the main thread, so store small things only, typically up to around 5 MB per origin.
setItemthrows aQuotaExceededErrorwhen storage is full, and can throw in some privacy modes, so wrap writes intry/catchwhen failure is possible.- It's available only to the page's own scripts on the main thread, not in Web Workers or service workers.
- Any script running on your page can read it, including an injected one, so never store secrets such as session tokens there.
The storage event
When one tab changes localStorage, every other tab of the same origin receives a storage event, while the tab that made the change doesn't. The event has key (null after clear()), oldValue, newValue, storageArea and url. This makes localStorage a simple way to keep tabs in sync, for example logging out everywhere at once:
window.addEventListener("storage", (event) => {
if (event.key === "app:prefs") applyPrefs(JSON.parse(event.newValue ?? "{}"));
if (event.key === "app:session" && event.newValue === null) showLoggedOutScreen();
});
For general messaging between tabs, BroadcastChannel (article 120) is the purpose-built tool.
Cookies
A cookie is a small named value that the browser stores and automatically sends to the server in the Cookie header of every matching request. Servers set cookies with the Set-Cookie response header. This is how sessions and logins usually work. JavaScript can also read and write cookies through document.cookie, an old interface with unusual behavior:
- Reading returns all cookies visible to the page as one string,
"name=value; name2=value2", with no attributes. - Writing sets one cookie, with optional attributes after semicolons. It doesn't replace the other cookies.
The values can't contain semicolons, commas or whitespace, so encode them:
// What reading document.cookie returns: just "name=value" pairs, no attributes
function parseCookies(cookieString) {
const cookies = new Map();
for (const pair of cookieString.split("; ")) {
const eq = pair.indexOf("=");
if (eq === -1) continue;
cookies.set(pair.slice(0, eq), decodeURIComponent(pair.slice(eq + 1)));
}
return cookies;
}
// What you assign to document.cookie: one cookie plus its attributes
function serializeCookie(name, value, { maxAge, path = "/", domain, secure = true, sameSite = "Lax" } = {}) {
let cookie = `${name}=${encodeURIComponent(value)}`;
if (maxAge !== undefined) cookie += `; max-age=${maxAge}`;
if (path) cookie += `; path=${path}`;
if (domain) cookie += `; domain=${domain}`;
if (secure) cookie += "; secure";
if (sameSite) cookie += `; samesite=${sameSite}`;
return cookie;
}
console.log(serializeCookie("theme", "dark mode; high contrast", { maxAge: 60 * 60 * 24 * 365 }));
console.log(serializeCookie("theme", "", { maxAge: 0 })); // deleting = expiring now
const jar = parseCookies("theme=dark%20mode%3B%20high%20contrast; lang=en; cart=3");
console.log(jar.get("theme"), jar.get("lang"), jar.size);
theme=dark%20mode%3B%20high%20contrast; max-age=31536000; path=/; secure; samesite=Lax
theme=; max-age=0; path=/; secure; samesite=Lax
dark mode; high contrast en 3
In a browser, document.cookie = serializeCookie(...) sets the cookie, and parseCookies(document.cookie) reads them all.
Cookie attributes
| Attribute | Effect |
|---|---|
max-age=seconds / expires=date | how long to keep it; without either, it's a session cookie, deleted when the browser session ends. max-age=0 deletes it |
path=/ | URL path prefix that can see the cookie; the default is the current page's directory |
domain=example.com | share with subdomains (shop.example.com, api.example.com); by default, only the exact host |
secure | sent only over HTTPS |
samesite=Strict / Lax / None | whether it's sent with requests from other sites. Lax (the default in modern browsers) blocks most cross-site requests except top-level navigation, which mitigates CSRF attacks. None requires secure |
HttpOnly | can only be set by the server; hides the cookie from document.cookie entirely |
To delete or overwrite a cookie, you must use the same name, path and domain it was set with.
Cookies have a size limit of about 4 KB each, and they cost bandwidth on every request, so use them only for data the server needs. Session identifiers should be HttpOnly; Secure; SameSite=Lax cookies set by the server. That way, injected scripts can't steal them. Browsers increasingly restrict third-party cookies (cookies of other sites embedded in a page) for privacy.
The Cookie Store API is a modern, promise-based alternative that is supported in all major browsers since 2025, and it also works in service workers:
await cookieStore.set({ name: "theme", value: "dark", expires: Date.now() + 365 * 864e5 });
const theme = await cookieStore.get("theme"); // { name, value, path, sameSite, ... } or null
await cookieStore.delete("theme");
cookieStore.addEventListener("change", (event) => console.log(event.changed, event.deleted));
IndexedDB
For real amounts of data, such as offline copies of documents, cached API results or large blobs, browsers provide IndexedDB, a transactional database of JavaScript objects:
- Asynchronous, so it doesn't block the page, and available in workers.
- Stores anything the structured clone algorithm supports (article 116): objects, arrays, Dates, Maps, Blobs, typed arrays.
- Object stores hold records by key; indexes look records up by other properties; all operations run in transactions.
- Large quotas, typically a sizeable share of free disk space.
The API is old and based on request objects and events rather than promises. A tiny helper turns requests into promises:
function request(req) {
return new Promise((resolve, reject) => {
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
function transactionDone(tx) {
return new Promise((resolve, reject) => {
tx.oncomplete = () => resolve();
tx.onabort = () => reject(tx.error);
});
}
Opening and versioning
A database has a name and an integer version. The structure (stores and indexes) can only change inside the upgradeneeded event, which fires when you open the database with a higher version than the one on disk. Checking oldVersion lets each user's database upgrade step by step, from whatever version it was at:
function openDatabase() {
const req = indexedDB.open("tea-shop", 2);
req.onupgradeneeded = (event) => {
const db = req.result;
if (event.oldVersion < 1) { // brand-new database
const store = db.createObjectStore("teas", { keyPath: "sku" });
store.createIndex("byType", "type");
}
if (event.oldVersion < 2) { // added in version 2
req.transaction.objectStore("teas").createIndex("byPrice", "price");
}
};
return request(req);
}
const db = await openDatabase();
keyPath: "sku" means each record's sku property is its key. Alternatively, { autoIncrement: true } generates numeric keys.
Reading and writing in transactions
const tx = db.transaction("teas", "readwrite");
const store = tx.objectStore("teas");
store.put({ sku: "g1", name: "Sencha", type: "green", price: 9.5, added: new Date() });
store.put({ sku: "g2", name: "Gyokuro", type: "green", price: 24 });
store.put({ sku: "b1", name: "Assam", type: "black", price: 7 });
await transactionDone(tx); // all three are saved, or none
const teas = db.transaction("teas").objectStore("teas"); // read-only by default
(await request(teas.get("g1"))).added instanceof Date; // true: structured clone keeps Dates
await request(teas.index("byType").getAll("green")); // Sencha, Gyokuro
await request(teas.index("byPrice").getAll(IDBKeyRange.bound(5, 10))); // Assam, Sencha
await request(teas.count()); // 3
putinserts or replaces;addfails with aConstraintErrorif the key exists, which aborts the transaction;delete(key)andclear()remove records.IDBKeyRange.bound,lowerBound,upperBoundandonlyselect key ranges.- Writing in a
"readonly"transaction throws aReadOnlyError.
A cursor walks records one at a time, in key order or reversed with "prev", without loading them all into memory:
const cursorRequest = db.transaction("teas").objectStore("teas").index("byPrice").openCursor(null, "prev");
cursorRequest.onsuccess = () => {
const cursor = cursorRequest.result;
if (!cursor) return; // no more records
console.log(cursor.value.name, cursor.value.price); // Gyokuro 24, Sencha 9.5, Assam 7
cursor.continue(); // fires onsuccess again with the next record
};
The auto-commit trap
A transaction commits automatically as soon as it has no pending requests and control returns to the event loop. If you await something unrelated, such as a fetch or a timer, in the middle of a transaction, it commits, and the next request throws a TransactionInactiveError. Fetch your data first, then open the transaction and do all its database work together.
Because the raw API is verbose, most projects use a small promise wrapper library such as idb, or a higher-level library such as Dexie. The concepts (versions, stores, indexes, transactions) stay the same.
Other storage, and quotas
- The Cache API (
caches.open(name)) stores HTTPRequest/Responsepairs. It's used mainly by service workers to make sites work offline. - The Origin Private File System (
navigator.storage.getDirectory()) offers fast, private file storage, used for example by SQLite compiled to WebAssembly. navigator.storage.estimate()reports usage and quota, andnavigator.storage.persist()asks the browser not to evict the origin's data when disk space runs low. Without it, storage is "best effort" and may be cleared under pressure. Safari can also delete script-writable storage for sites the user hasn't visited in a while.
Common questions
Where should I store a login token?
Preferably not in JavaScript-readable storage at all. Use an HttpOnly; Secure; SameSite cookie set by the server, which scripts (including injected ones) can't read. If an API requires bearer tokens, keep them in memory and refresh them through such a cookie.
Why does localStorage.getItem("count") + 1 give "11"?
Storage values are always strings. Convert when reading: Number(localStorage.getItem("count") ?? 0) + 1.
Why didn't setting document.cookie remove my other cookies?
Each assignment sets one cookie; it isn't a replacement of the whole string. To remove a cookie, set it again with the same name, path and domain, and max-age=0.
localStorage or IndexedDB?
localStorage for small, simple settings read at startup. IndexedDB for anything large or structured, anything needed in workers, or data you query by fields.
Summary
localStorage(per origin, persistent) andsessionStorage(per tab) store strings synchronously. Wrap them with JSON and error handling, and keep the data small and non-secret.- The
storageevent notifies other tabs oflocalStoragechanges. - Cookies travel with every request.
document.cookiereads all of them and writes one at a time; attributes control lifetime (max-age), scope (path,domain) and security (secure,samesite, server-onlyHttpOnly).cookieStoreis the promise-based API. - IndexedDB is an asynchronous, transactional object database: version upgrades create stores and indexes;
get,getAll,put,add, key ranges and cursors read and write data; transactions auto-commit when idle. - The Cache API, OPFS and
navigator.storageround out client storage, which may be evicted unless persistence is granted.
Practice Questions
Two tabs show the same site. Tab A runs sessionStorage.setItem("step", "2"). What does Tab B's sessionStorage.getItem("step") return?
Answer
null (assuming Tab B never set it). Each tab has its own sessionStorage. With localStorage, Tab B would see "2" and receive a storage event.
Write the document.cookie assignment that stores lang=fr for the whole site for 30 days, over HTTPS only.
Answer
document.cookie = `lang=fr; max-age=${60 * 60 * 24 * 30}; path=/; secure; samesite=Lax`;
This code throws a TransactionInactiveError on the put. Why?
const store = db.transaction("notes", "readwrite").objectStore("notes");
const fresh = await fetch("/api/note/1").then((r) => r.json());
store.put(fresh);
Answer
The transaction had no pending requests while fetch was awaited, so it auto-committed. Fetch the data first, then create the transaction and call put without awaiting anything unrelated in between.
You add a new index in the next release. What must change in the indexedDB.open call, and where does the index get created?
Answer
Increase the version number passed to indexedDB.open. Create the index in the upgradeneeded handler, inside a check such as if (event.oldVersion < 3), using req.transaction.objectStore(...).createIndex(...).
Previous: Server-Sent Events and WebSockets: Real-Time Updates in the Browser
Next: Web Workers and Messaging: Threads, postMessage, Transferables and BroadcastChannel

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.