Skip to curriculum
Jump to the editor

18.2. localStorage with expiry

Easy
Topics
15–25 min

localStorage keeps everything until someone removes it. A cached API response, a "don't show this banner for a week" flag or a draft should not live forever, but localStorage has no expiry. The usual fix is to store the expiry time next to the value and check it on every read.

Write createExpiringStorage(storage) in expiring-storage.js. It wraps any object with the Storage API (localStorage, sessionStorage or a stand-in) and returns an object whose items can expire.

Signature

JAVASCRIPT
function createExpiringStorage(storage) // returns { setItem, getItem, removeItem, prune }

store.setItem(key, value, ttl)  // ttl in ms; missing or Infinity: never expires; NaN or -Infinity: RangeError. Returns true or false.
store.getItem(key)              // the value, or null when missing or expired
store.removeItem(key)
store.prune()                   // removes expired items; returns how many

Each item is stored under its own key as the JSON text of { "value": …, "expiresAt": … }. expiresAt is a Date.now() time in milliseconds (Date.now() + ttl), or null when the item never expires.

Requirements

  1. setItem writes the entry through storage.setItem and returns true; getItem returns the value before it expires.
  2. Values keep their JSON type: numbers, booleans, null, arrays and objects come back as they went in.
  3. An item expires when Date.now() >= expiresAt. Then getItem returns null and removes the entry from storage.
  4. Without a ttl (or with Infinity), the item never expires and expiresAt is null.
  5. A finite ttl of 0 or less means the item is already expired. (-Infinity is not accepted: see rule 11.)
  6. Setting a key again replaces its value and its expiry.
  7. A missing key reads as null. An item this wrapper did not write (not JSON, or not an object with an expiresAt that is a number or null) also reads as null, and is left in storage untouched.
  8. Every read returns a fresh copy: changing a returned object does not change the next read.
  9. Everything lives in storage: a new wrapper over the same storage (after a page reload) reads the same items and expiry times.
  10. When storage.setItem throws (a full storage throws QuotaExceededError), setItem returns false and does not throw. A value that JSON.stringify cannot handle still throws.
  11. A ttl that is not a number throws TypeError; NaN and -Infinity throw RangeError, and nothing is stored. (JSON has no infinities: an expiry of -Infinity would be written as null, which means "never expires".)
  12. prune() removes every expired item this wrapper wrote, keeps the others (live items and items it did not write), and returns how many it removed.
  13. Use only the methods of the storage you are given, never a global localStorage.

Examples

JAVASCRIPT
const store = createExpiringStorage(localStorage);
store.setItem("token", "abc", 60_000);   // true
store.getItem("token");                  // "abc"
// 60 seconds later
store.getItem("token");                  // null, and the entry is gone from localStorage
JAVASCRIPT
store.setItem("prefs", { theme: "dark" });   // never expires
localStorage.getItem("prefs");               // '{"value":{"theme":"dark"},"expiresAt":null}'
JAVASCRIPT
localStorage.setItem("legacy", "plain text");
store.getItem("legacy");                     // null, and "legacy" is still in localStorage
store.setItem("huge", "x".repeat(10_000_000)); // false when the storage is full
store.setItem("gone", 1, -5);              // true: already expired, getItem("gone") is null
store.setItem("bad", 1, -Infinity);        // throws RangeError, like NaN

Environment

  • Plain JavaScript in a browser page; the tests call the global createExpiringStorage from expiring-storage.js.
  • The tests run in a sandboxed frame, where the real localStorage throws, so they pass an in-memory object with the same methods: getItem, setItem, removeItem, key(index), length and clear. It can be made small, to act like a full storage.
  • The tests run on a virtual clock that replaces Date.now. No timers are needed.
  • Out of scope: the storage event across tabs, and sharing keys with a prefix.

Hints

  1. A page reload creates a new wrapper. Where must the expiry time live so the new one knows it?
  2. When you remove keys while you walk storage.key(0), storage.key(1), … what happens to the index of the next key?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…