JavaScript LocalStorage with TTL Expiration
Store data in browser localStorage with TTL expiration: expiry wrappers, lazy cleanup, quota handling, stale-while-revalidate and cross-tab sync
Overview
localStorage keeps whatever you write until someone deletes it; there’s no expiration built in. This recipe wraps it with TTL (time-to-live) support so entries age out on their own: set/get with an expiry timestamp, lazy cleanup on read, quota handling, a stale-while-revalidate variant for API caching, and cross-tab sync.
For plain server-driven caching the browser already has HTTP cache headers. This recipe is for the client-side cache you own: API responses you don’t want to refetch every page load, feature flags, wizard state that should die after an hour.
When to Use
- Client-side caching with automatic expiration (API responses, config, feature flags)
- User preferences or UI state that should reset after a period
- An offline-first app needing stale-while-revalidate reads
- Session-like storage that survives reloads but not forever
And when not to reach for it:
| Situation | Better tool |
|---|---|
| Tokens, credentials, PII | sessionStorage, memory, or httpOnly cookies — localStorage is readable by any script on the origin |
| Data over a few hundred KB | IndexedDB — localStorage caps around 5-10 MB and blocks the main thread |
| Data needing transactions or indexes | IndexedDB |
| Cache correctness tied to the server | HTTP cache headers / service worker — client clocks can be wrong |
| Multi-tab writes that must stay in sync | The storage event helps, but for shared state a server or BroadcastChannel-driven design is cleaner |
Solution
1. Basic localStorage with TTL
const storage = {
prefix: "ttl:",
set(key, value, ttlMs = 60000) {
const item = {
value,
expiry: Date.now() + ttlMs
};
localStorage.setItem(this.prefix + key, JSON.stringify(item));
},
get(key) {
const raw = localStorage.getItem(this.prefix + key);
if (!raw) return null;
try {
const item = JSON.parse(raw);
if (Date.now() > item.expiry) {
localStorage.removeItem(this.prefix + key);
return null;
}
return item.value;
} catch (err) {
localStorage.removeItem(this.prefix + key);
return null;
}
},
remove(key) {
localStorage.removeItem(this.prefix + key);
},
clear() {
// Only OUR keys — localStorage.clear() would wipe the whole origin
Object.keys(localStorage)
.filter(k => k.startsWith(this.prefix))
.forEach(k => localStorage.removeItem(k));
}
};
// Usage: cache for 5 minutes
storage.set("api-data", { users: [1, 2, 3] }, 5 * 60 * 1000);
const data = storage.get("api-data");
console.log(data);
Two things worth noticing even in this minimal version: the try/catch on parse (other code, or an older deploy, may have left non-JSON data under your keys) and the scoped clear(). A bare localStorage.clear() deletes everything on the origin: other parts of the app, other libraries, the works.
2. Storage wrapper with cleanup and quota handling
class TTLStorage {
constructor(prefix = "ttl:") {
this.prefix = prefix;
// In-memory fallback: private mode / disabled storage
this.memoryFallback = new Map();
this.available = this.checkAvailable();
}
checkAvailable() {
try {
const probe = this.prefix + "__probe__";
localStorage.setItem(probe, "1");
localStorage.removeItem(probe);
return true;
} catch (err) {
return false;
}
}
set(key, value, ttlMs = 300000) {
const item = {
value: JSON.stringify(value),
expiry: Date.now() + ttlMs,
created: Date.now()
};
if (!this.available) {
this.memoryFallback.set(this.prefix + key, item);
return true;
}
try {
localStorage.setItem(this.prefix + key, JSON.stringify(item));
return true;
} catch (err) {
if (err.name === "QuotaExceededError") {
this.cleanup();
try {
localStorage.setItem(this.prefix + key, JSON.stringify(item));
return true;
} catch (err2) {
console.error("Storage quota exceeded even after cleanup");
return false;
}
}
console.error("Failed to set item:", err);
return false;
}
}
get(key, fallback = null) {
const fullKey = this.prefix + key;
if (!this.available) {
const item = this.memoryFallback.get(fullKey);
if (!item) return fallback;
return Date.now() > item.expiry ? fallback : JSON.parse(item.value);
}
const raw = localStorage.getItem(fullKey);
if (!raw) return fallback;
try {
const item = JSON.parse(raw);
if (Date.now() > item.expiry) {
localStorage.removeItem(fullKey);
return fallback;
}
return JSON.parse(item.value);
} catch (err) {
localStorage.removeItem(fullKey);
return fallback;
}
}
has(key) {
return this.get(key, Symbol.for("ttl:miss")) !== Symbol.for("ttl:miss");
}
remove(key) {
if (this.available) localStorage.removeItem(this.prefix + key);
this.memoryFallback.delete(this.prefix + key);
}
cleanup() {
if (!this.available) return;
for (const key of Object.keys(localStorage)) {
if (!key.startsWith(this.prefix)) continue;
const raw = localStorage.getItem(key);
if (!raw) continue;
try {
const item = JSON.parse(raw);
if (Date.now() > item.expiry) {
localStorage.removeItem(key);
}
} catch (err) {
localStorage.removeItem(key);
}
}
}
clearAll() {
for (const key of Object.keys(localStorage)) {
if (key.startsWith(this.prefix)) localStorage.removeItem(key);
}
this.memoryFallback.clear();
}
size() {
return Object.keys(localStorage)
.filter(k => k.startsWith(this.prefix)).length;
}
}
const cache = new TTLStorage("app:");
// Cache API response for 10 minutes
cache.set("users", [{ id: 1, name: "Alice" }], 10 * 60 * 1000);
const users = cache.get("users", []);
3. Stale-while-revalidate for API responses
class SWRStorage {
constructor(prefix = "swr:") {
this.prefix = prefix;
}
set(key, value, ttlMs = 60000, staleMs = 300000) {
const item = {
value: JSON.stringify(value),
expiry: Date.now() + ttlMs,
staleUntil: Date.now() + ttlMs + staleMs
};
localStorage.setItem(this.prefix + key, JSON.stringify(item));
}
get(key) {
const raw = localStorage.getItem(this.prefix + key);
if (!raw) return { data: null, stale: false, expired: true };
try {
const item = JSON.parse(raw);
const now = Date.now();
if (now > item.staleUntil) {
localStorage.removeItem(this.prefix + key);
return { data: null, stale: false, expired: true };
}
if (now > item.expiry) {
return { data: JSON.parse(item.value), stale: true, expired: false };
}
return { data: JSON.parse(item.value), stale: false, expired: false };
} catch (err) {
localStorage.removeItem(this.prefix + key);
return { data: null, stale: false, expired: true };
}
}
}
const swr = new SWRStorage();
swr.set("config", { theme: "dark" }, 60000, 300000);
async function getConfig() {
const { data, stale, expired } = swr.get("config");
if (expired) {
const fresh = await fetch("/api/config").then(r => r.json());
swr.set("config", fresh, 60000, 300000);
return fresh;
}
if (stale) {
// Serve what we have, refresh in the background
fetch("/api/config")
.then(r => r.json())
.then(fresh => swr.set("config", fresh, 60000, 300000));
return data;
}
return data;
}
The user sees last session’s config instantly while a fresh copy loads behind their back; that’s the cache-aside pattern applied to browser storage, and the server-side version works the same way.
SWRStorage is intentionally minimal — in production it inherits the same guardrails as TTLStorage: the availability probe, the memory fallback, and a cleanup() scoped to its own prefix.
4. Cross-tab sync with the storage event
// Any tab that writes or removes a key notifies the others.
window.addEventListener("storage", (event) => {
if (!event.key || !event.key.startsWith("app:")) return;
if (event.newValue === null) {
console.log(`Key ${event.key} was removed in another tab`);
return;
}
try {
const item = JSON.parse(event.newValue);
if (item.expiry && Date.now() > item.expiry) return; // expired write, ignore
console.log(`Key ${event.key} updated in another tab:`, item.value);
} catch (err) {
// Not one of ours
}
});
The storage event only fires in other tabs (the tab that wrote gets nothing), so it’s the right tool for syncing state, not for reacting to your own writes.
5. Periodic cleanup scoped to your prefix
function cleanupExpiredEntries(prefix = "ttl:") {
for (const key of Object.keys(localStorage)) {
if (!key.startsWith(prefix)) continue; // never touch other code's keys
const raw = localStorage.getItem(key);
if (!raw) continue;
try {
const item = JSON.parse(raw);
if (item.expiry && Date.now() > item.expiry) {
localStorage.removeItem(key);
}
} catch (err) {
// Corrupt or foreign entry under our prefix — drop it
localStorage.removeItem(key);
}
}
}
window.addEventListener("DOMContentLoaded", () => cleanupExpiredEntries("app:"));
Skip the setInterval version unless the page genuinely stays open for hours (a dashboard, a kiosk). On normal page loads the lazy cleanup inside get() already does the job.
How It Works
The trick is the metadata wrapper: instead of storing the value bare, you store { value, expiry }. Every read compares Date.now() against expiry, and past it the entry deletes itself and reports a miss. That’s lazy expiration: nothing scans storage until a read or an explicit cleanup() touches it.
A few details that matter in production:
- Double serialization: the class stringifies the value inside the wrapper, so
set("n", 0)andset("x", null)survive a round-trip without colliding with your fallback logic. - Validate the payload you read. If an older deploy — or another library on the same origin — wrote a bare value under your keys,
item.expirycomes backundefined,Date.now() > undefinedisfalse, and the entry is treated as fresh forever while returningitem.valueasundefined. Atypeof item.expiry === "number"check inget()turns those foreign entries into clean misses thatcleanup()can remove. - JSON decides what you can store: a
Datecomes back as an ISO string, andMap,Set,undefinedand functions get silently dropped or mangled byJSON.stringify. Keep cached values to plain data — objects, arrays, numbers, strings, booleans — or serialize richer types yourself. - Prefix everything (
app:userinstead ofuser) because it keeps cleanup cheap, prevents collisions with other code on the origin, and letsstorageevents filter quickly. - Probe once, then trust the flag:
checkAvailable()writes and removes a probe key at construction. When it fails, the class quietly swaps storage for an in-memoryMap, so the cache still works for the life of the page and just doesn’t survive a reload. That’s the right trade for private mode: degraded persistence beats a crashed feature. - Watch the clock:
Date.now()follows the user’s system clock, so if they jump it forward entries expire early, and backward they live longer. For “30 minutes of real elapsed time” there’s no fix inside localStorage; keep TTLs short enough that drift doesn’t hurt. storageevents fire cross-tab only, so writes in tab A reach tabs B and C, which is handy for invalidating a shared cache entry. If you need richer tab-to-tab messaging rather than invalidation,BroadcastChannelis the cleaner API, but it doesn’t tell you when another tab deletes a key the waystoragedoes.
Variants
| Approach | Complexity | What it adds | Use When |
|---|---|---|---|
| Basic TTL wrapper | Low | Set/get/remove with expiry | Simple caching, prototypes |
| TTLStorage class | Medium | Quota retry, cleanup, prefix, memory fallback | Production apps |
| SWR pattern | Medium | Serves stale + background refresh | API response caching |
storage event sync | Medium | Cross-tab invalidation | Multi-tab apps |
| sessionStorage + TTL | Low | Same wrappers, dies with the tab | Per-session cache |
For sessionStorage, swap localStorage for sessionStorage in any of the wrappers; the API is identical and only the lifetime changes.
Best Practices
- Always store an
expirytimestamp; a bare value persists forever. - Namespace keys with a prefix; cleanup,
clear(), andstorageevents all depend on it. - Wrap
setItemintry/catch: private mode and full quota both throw. - Lazy-expire on read; add load-time
cleanup()only for apps that accumulate many keys. - Never store tokens or PII; any script on the origin (including injected ones) can read localStorage.
- Keep TTLs realistic, since a 30-day TTL is a cache that never expires in practice anyway.
- Prefer SWR for data the UI can paint stale; prefer a hard TTL for anything that must not look old.
Common Mistakes
localStorage.clear()as a reset. It deletes every key on the origin; your feature just wiped someone else’s data. Clear only your prefix.- No
try/catcharoundsetItem. Safari private mode and a full quota throw; unhandled, the write path crashes the feature. - Storing the raw value without metadata. Six months from now you won’t be able to tell a cache entry from a typo.
- Parsing without a fallback.
JSON.parseon a corrupt entry throws; delete the key and move on. - Cleaning up across the whole origin. A cleanup loop that ignores prefixes will happily parse (and delete) keys it doesn’t own.
- Treating the expiry as a guarantee. The entry stays on disk until something reads it or cleanup runs; expired ≠ gone.
See Also
Frequently Asked Questions
How much data can I store in localStorage?
Most browsers allow 5-10 MB per origin, and the limit counts UTF-16 characters, not bytes, so emoji-heavy JSON costs double. Handle QuotaExceededError and keep cache entries small; anything bulkier belongs in IndexedDB.
Should I use localStorage or sessionStorage?
localStorage for things that should outlive the tab (cached responses, preferences). sessionStorage for things tied to the visit (form drafts, one-off wizard state). The TTL wrappers here work with either; it's a one-line swap.
What happens in private browsing mode?
Safari historically threw QuotaExceededError on every write; modern browsers allow a small quota instead. Either way, assume writes can fail; the checkAvailable() + in-memory Map pattern above keeps the app working, you just lose persistence.
Can I use IndexedDB instead?
Yes, and past a few hundred KB you should. IndexedDB gives you real queries, transactions, and hundreds of MB; in exchange you get an async API and a good deal more code. localStorage-with-TTL is the right size for simple key-value caching you'd rather keep synchronous.
Does an expired entry get deleted automatically?
No. Lazy expiration means the entry is deleted the next time get() touches it (or cleanup() runs). If you need hard guarantees about data not lingering on disk, localStorage is the wrong store entirely; that data shouldn't be written client-side at all.
How do I keep tabs in sync when a key expires?
By listening for the storage event (example 4): when tab A removes or overwrites a key, every other open tab gets the event and can drop its in-memory copy or re-render.
Related Resources
Cache-Aside Pattern
Load data into the cache on demand from the backing store. A caching pattern that gives the application full control over what and when to cache.
RecipeJavaScript Service Worker Offline Caching for PWA
Serve your web app offline with Service Workers and the Cache API: precaching, runtime caching strategies and a fallback page.
RecipeMulti-Level Cache with In-Memory L1 and Redis L2
Cut Redis round-trips on hot keys: in-memory L1 for microsecond reads, Redis L2 for shared state, and pub/sub invalidation across instances
GuideComplete Guide to Cache Invalidation
Cache invalidation strategies: TTL, event-driven, versioned keys, tag-based purging, write-through, multi-tier, race conditions and consistency.
GuideComplete Guide to Application-Level Caching
In-memory, distributed and hybrid caches at the app layer: LRU, TTL, two-tier strategies, sizing, thread safety and invalidation patterns.
RecipeHTTP Cache-Control Headers for APIs and Static Assets
Set Cache-Control, ETag, and Last-Modified headers to control browser and CDN caching for API responses and static assets