JavaScript

LocalStorage with Expiry

by @admin
12h ago
Apr 28, 2026
Public
Extends localStorage with TTL (time-to-live) support. setItem stores a value alongside an expiry timestamp. getItem returns null and removes the key if the TTL has elapsed. Useful for caching API responses client-side, storing ephemeral UI state, and implementing remember-me tokens without a backend session.
JavaScript
const storage = {
  set(key, value, ttlMs) {
    const item = { value, expires: ttlMs ? Date.now() + ttlMs : null };
    localStorage.setItem(key, JSON.stringify(item));
  },
  get(key) {
    const raw = localStorage.getItem(key);
    if (!raw) return null;
    const { value, expires } = JSON.parse(raw);
    if (expires && Date.now() > expires) {
      localStorage.removeItem(key);
      return null;
    }
    return value;
  },
  remove(key) {
    localStorage.removeItem(key);
  },
};

// Usage
storage.set('user', { name: 'Alice' }, 30 * 60 * 1000); // 30 min TTL
console.log(storage.get('user')); // { name: 'Alice' } (within 30 min)
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.