← Back to Blog
Code Snippets June 25, 2026

LocalStorage with Automatic Expiration (TTL) — JavaScript

🌐 Code Snippet — June 25, 2026

LocalStorage with Automatic Expiration (TTL) — JavaScript

Vanilla \localStorage\ has no expiration. Every frontend dev eventually writes this wrapper — here's a clean, copy-paste-ready version:

\\\javascript
class StorageManager {
constructor(prefix = "app_") { this.prefix = prefix; }

set(name, value, ttlSeconds = 3600) {
localStorage.setItem(this.prefix + name, JSON.stringify({
value: JSON.stringify(value),
expiry: Date.now() + ttlSeconds 1000
}));
}

get(name) {
const raw = localStorage.getItem(this.prefix + name);
if (!raw) return null;
try {
const { value, expiry } = JSON.parse(raw);
if (Date.now() > expiry) {
localStorage.removeItem(this.prefix + name);
return null;
}
return JSON.parse(value);
} catch {
localStorage.removeItem(this.prefix + name);
return null;
}
}

tidy() {
const now = Date.now();
for (let i = localStorage.length - 1; i >= 0; i--) {
const key = localStorage.key(i);
if (!key?.startsWith(this.prefix)) continue;
try {
const { expiry } = JSON.parse(localStorage.getItem(key));
if (now > expiry) localStorage.removeItem(key);
} catch { localStorage.removeItem(key); }
}
}
}

// Usage:
const cache = new StorageManager("session_");
cache.set("token", { access: "abc123" }, 900); // 15min TTL
const token = cache.get("token"); // null if expired
cache.tidy(); // purge expired keys
\
\\

💡
Bookmark this — covers 90% of expiring storage cases without a library.*