Core differences: scope, lifetime and format
| Mechanism | Access scope | Lifetime | Data | Typical use |
|---|---|---|---|---|
| localStorage | Origin | Across visits | Text | Preferences |
| sessionStorage | Origin and tab | Tab session | Text | Form step |
| Cookies | Host, Domain, Path | Session or expiry | Text | HTTP session |
| IndexedDB | Origin | Across visits | Objects, Blob | Offline documents |
Web Storage consists of localStorage and sessionStorage. Both store string key-value pairs through synchronous APIs. IndexedDB supports structured objects, Blob values, indexes and transactions. Cookies store small text values associated with HTTP. [1][5][8]
An origin combines scheme, host and port: https://app.example.com and https://admin.example.com have separate Web Storage and IndexedDB. Cookies instead follow host or Domain and Path rules plus security restrictions. [4][5]
localStorage: preferences across visits
const THEME_KEY = "app:theme:v1";
function isTheme(value) {
return value === "light" || value === "dark";
}
function readTheme() {
try {
const value = localStorage.getItem(THEME_KEY);
return isTheme(value) ? value : "light";
} catch {
return "light";
}
}
function saveTheme(theme) {
if (!isTheme(theme)) {
return false;
}
try {
localStorage.setItem(THEME_KEY, theme);
return true;
} catch {
return false;
}
}
saveTheme("dark");
console.log(readTheme());
Theme, table density and filter preferences can survive a reload and a browser restart. localStorage has no built-in TTL, but it is not permanent: users can clear it and browsers can restrict access. [1][3]
The example accepts only supported theme values and catches read and write failures. The app still works with a default when storage is unavailable. Large JSON objects require synchronous serialization and parsing; writing on every keystroke can delay work on the main thread. [1]
sessionStorage: forms and per-tab state
const STEP_KEY = "checkout:step:v1";
function readStep() {
try {
const step = Number(sessionStorage.getItem(STEP_KEY));
return Number.isInteger(step) && step >= 1 && step <= 3 ? step : 1;
} catch {
return 1;
}
}
function saveStep(step) {
if (!Number.isInteger(step) || step < 1 || step > 3) {
return false;
}
try {
sessionStorage.setItem(STEP_KEY, String(step));
return true;
} catch {
return false;
}
}
saveStep(2);
console.log(readStep());
sessionStorage is scoped to the origin and top-level browsing context, typically a tab. It survives reloads but ordinarily ends with the tab session; browser session restoration can restore it. A new window with an opener may receive an initial copy, after which changes remain independent. [2]
For a multi-step form, save the current step rather than passwords or payment details. This example validates the step range and handles inaccessible storage. Multiple forms in one tab need separate keys. Open independent windows with noopener to avoid copying their initial state.
Cookies: HTTP state and authentication
Set-Cookie: __Host-session=REPLACE_WITH_RANDOM_ID; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=1800
The server sets cookies with Set-Cookie. Browsers attach matching cookies according to host, path, SameSite, credentials settings and privacy policies. Unlike Web Storage, this does not require manually copying a session ID into an Authorization header. Unnecessary cookies add request overhead. [5]
The response header below illustrates a server-generated random session identifier (placeholder value). Secure requires a secure connection, HttpOnly prevents JavaScript from reading the cookie, and SameSite=Lax restricts some cross-site requests. The __Host- prefix requires Secure, Path=/ and no Domain. Max-Age is in seconds, but the server must independently enforce session expiry and revocation. [5][6]
IndexedDB: an offline database
function openNotes() {
return new Promise((resolve, reject) => {
const request = indexedDB.open("notes-demo", 1);
request.onupgradeneeded = () => {
const store = request.result.createObjectStore("notes", {
keyPath: "id",
});
store.createIndex("updatedAt", "updatedAt");
};
request.onblocked = () => console.warn("Close other tabs to upgrade");
request.onerror = () => reject(request.error);
request.onsuccess = () => {
const db = request.result;
db.onversionchange = () => db.close();
resolve(db);
};
});
}
function saveNote(db, note) {
return new Promise((resolve, reject) => {
const tx = db.transaction("notes", "readwrite");
tx.oncomplete = () => resolve();
tx.onabort = () => reject(tx.error ?? new Error("Write aborted"));
tx.objectStore("notes").put(note);
});
}
function recentNotes(db, since) {
return new Promise((resolve, reject) => {
const tx = db.transaction("notes", "readonly");
const request = tx
.objectStore("notes")
.index("updatedAt")
.getAll(IDBKeyRange.lowerBound(since), 50);
tx.oncomplete = () => resolve(request.result);
tx.onabort = () => reject(tx.error ?? new Error("Read aborted"));
});
}
async function demoNotes() {
const db = await openNotes();
try {
await saveNote(db, {
id: "n1",
text: "Draft",
updatedAt: Date.now(),
});
return await recentNotes(db, Date.now() - 86400000);
} finally {
db.close();
}
}
demoNotes().then(console.log).catch(console.error);
IndexedDB supports keyed records, indexes and atomic operations within transactions. The example creates a notes store with id as its key and updatedAt as an index. Schema changes occur in onupgradeneeded when the version increases. Other tabs can block an upgrade, so close the connection on versionchange. [8]
Treat a write as successful only after the transaction's complete event, not after a single put request succeeds. The index query retrieves records from a given date; a sample limit of 50 avoids reading an entire large collection. Do not await a network request inside an active transaction: the transaction may finish automatically. [8][9]
Quotas, eviction and performance
async function storageStatus() {
const manager = navigator.storage;
if (!manager?.estimate) {
return null;
}
const { usage, quota } = await manager.estimate();
return {
usage,
quota,
persistent: manager.persisted ? await manager.persisted() : null,
};
}
// Call from an explicit save-offline action.
async function requestPersistence() {
return navigator.storage?.persist ? navigator.storage.persist() : false;
}
storageStatus().then(console.log).catch(console.error);
MDN describes the usual Web Storage allowance as 5 MiB each for localStorage and sessionStorage per origin; available space and accounting can vary with browser settings. Keep cookies small, typically a few KiB, rather than storing documents in them. IndexedDB uses browser-managed origin storage shared with other facilities such as the Cache API. [3][5]
navigator.storage.estimate() provides approximate usage and quota, not a guarantee that the next write succeeds or a separate localStorage counter. persist() can reduce automatic eviction under storage pressure, but cannot prevent manual clearing. Handle QuotaExceededError, remove expendable data and sync critical content to a server or offer an export. [3][10][11]
Cross-tab synchronization, privacy and conflicts
// Uses THEME_KEY, readTheme() and saveTheme() from section 2.
function applyTheme(theme) {
document.documentElement.dataset.theme = theme;
}
function changeTheme(theme) {
if (!isTheme(theme)) {
return false;
}
applyTheme(theme);
return saveTheme(theme);
}
window.addEventListener("storage", (event) => {
if (
event.storageArea === localStorage &&
(event.key === THEME_KEY || event.key === null)
) {
applyTheme(readTheme());
}
});
applyTheme(readTheme());
The storage event notifies other documents sharing the localStorage area. It does not fire in the window performing the write. For sessionStorage it is limited to same-origin contexts within the same tab. This example updates local theme state directly and responds to changes or clear() in other tabs. [7]
A read-modify-write sequence in localStorage is not a cross-tab transaction. Concurrent writers can lose updates; use IndexedDB transactions for compound updates or server-side version checks. In cross-site embeds, storage may be partitioned or blocked. Do not assume a widget can read state written during a direct visit to its site. [8][12]
Security and application responsibilities
JavaScript running in the app's origin can read and modify localStorage, sessionStorage and IndexedDB. XSS can therefore expose or corrupt their contents. Do not make them the default home for session identifiers or refresh tokens. HttpOnly prevents direct cookie reads but malicious scripts can still issue authenticated requests. SameSite supplements CSRF protection rather than replacing tokens or appropriate origin verification. Authorization must be enforced on the server regardless of local state. [6][13][14]
An offline editor can use localStorage for theme, sessionStorage for view state, a session cookie for authentication and IndexedDB for documents and an outbox. The Cache API can hold HTTP responses such as application assets. An outbox still needs operation IDs, retry rules and conflict resolution; IndexedDB does not sync with a server automatically. Scope records by account and clear private data on logout according to product policy without silently discarding unsaved work. [8][15]
