Local Storage with Expiry
Local Storage with Expiry is a reusable JavaScript snippet. Extends localStorage to support expiring keys. Data is automatically removed after a specified TTL. The full implementation: const storage = { set(key, value, ttlMs = null) { const item = { value } if (ttlMs) item.expiry = Date.now() + ttlMs localStorage.setItem(key, JSON.stringify(item)) }, get(key) { const raw = localStorage.getItem(key) if (!raw) return null try { const item = JSON.parse(raw) if (item.expiry && Date.now() > item.expiry) { localStorage.removeItem(key) return null } return item.value } catch { return raw } }, remove(key) { localStorage.removeItem(key) }, clear() { localStorage.clear() }, isExpired(key) { const raw = localStorage.getItem(key) if (!raw) return true… This snippet uses only standard JavaScript with no dependencies, so it runs in modern browsers and Node.js alike. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.