18.2. localStorage with expiry
Topics
This question is in
18. URLs, storage and safe HTMLlocalStorage 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
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 manyEach 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
setItemwrites the entry throughstorage.setItemand returnstrue;getItemreturns the value before it expires.- Values keep their JSON type: numbers, booleans,
null, arrays and objects come back as they went in. - An item expires when
Date.now() >= expiresAt. ThengetItemreturnsnulland removes the entry from storage. - Without a ttl (or with
Infinity), the item never expires andexpiresAtisnull. - A finite ttl of 0 or less means the item is already expired. (
-Infinityis not accepted: see rule 11.) - Setting a key again replaces its value and its expiry.
- A missing key reads as
null. An item this wrapper did not write (not JSON, or not an object with anexpiresAtthat is a number ornull) also reads asnull, and is left in storage untouched. - Every read returns a fresh copy: changing a returned object does not change the next read.
- Everything lives in
storage: a new wrapper over the same storage (after a page reload) reads the same items and expiry times. - When
storage.setItemthrows (a full storage throwsQuotaExceededError),setItemreturnsfalseand does not throw. A value thatJSON.stringifycannot handle still throws. - A ttl that is not a number throws
TypeError;NaNand-InfinitythrowRangeError, and nothing is stored. (JSON has no infinities: an expiry of-Infinitywould be written asnull, which means "never expires".) 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.- Use only the methods of the storage you are given, never a global
localStorage.
Examples
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 localStoragestore.setItem("prefs", { theme: "dark" }); // never expires
localStorage.getItem("prefs"); // '{"value":{"theme":"dark"},"expiresAt":null}'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 NaNEnvironment
- Plain JavaScript in a browser page; the tests call the global
createExpiringStoragefromexpiring-storage.js. - The tests run in a sandboxed frame, where the real
localStoragethrows, so they pass an in-memory object with the same methods:getItem,setItem,removeItem,key(index),lengthandclear. 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
storageevent across tabs, and sharing keys with a prefix.
Hints
- A page reload creates a new wrapper. Where must the expiry time live so the new one knows it?
- 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