Storage TTL Cache (localStorage/sessionStorage)

intermediate
By FrontendAtlas Editorial · Updated Oct 10, 2026
Implement createTtlStorage(storage, now?) that returns { set, get, remove }. It should store JSON values with an optional TTL and automatically expire items when read. This mirrors real-world caching layers on top of localStorage/sessionStorage.

Arguments

  • storage: { getItem, setItem, removeItem } — A Storage-like object (localStorage/sessionStorage compatible).
  • now: () => number — Optional time provider (defaults to Date.now) for testing.

Returns

{ set: (key, value, ttlMs?) => void, get: (key) => any, remove: (key) => void } — A tiny TTL-aware cache wrapper.

Solution idea

Store a JSON envelope { v, exp } where exp is the absolute expiration timestamp or null. On get, parse the envelope, check exp, and delete expired or invalid entries.

Examples
const cache = createTtlStorage(localStorage);
cache.set('user', { id: 1 }, 5000);
cache.get('user');

cache.set('perm', 'ok'); // no expiry