Faizo

Writing · JavaScript · Web · State management

A stale browser tab deleted four hours of saved drafts

Two tabs, one localStorage key, and a save that wrote an old list over newer data. Making browser storage safe across tabs, plus two IndexedDB traps.

A user wrote in: they had saved four drafts in DWEEB over an afternoon, and now the list showed only two old ones plus the one they had just saved. Four hours of work, gone. Nothing had been deleted, nothing had errored, and the save had "worked".

It took a few minutes to guess and a headless browser to prove: they had two tabs open.

The bug

Browser-saved drafts lived in one localStorage key holding a JSON array. The app kept that array in a state store, loaded once at startup, and saving did the obvious thing:

// The bug: write this tab's in-memory view back as the whole list.
save(record) {
  const entries = [record, ...this.entries];
  localStorage.setItem(KEY, JSON.stringify(entries));
  this.entries = entries;
}

Every tab of the same origin shares one localStorage, but each tab has its own copy of this.entries. So:

  1. Tab A is opened in the morning. It loads two drafts into memory.
  2. The user works in tab B all afternoon and saves four more. Storage now holds six.
  3. They go back to tab A and save. Tab A writes its record plus its two, and replaces six drafts with three.

The in-memory copy is not the data. It is one tab's view of the data, and it goes stale the moment another tab writes.

The fix: read, modify, write

Every mutation now re-reads the stored list, applies its one change and writes that back. The in-memory copy is only ever updated from what was written:

function mutate(change) {
  let current;
  try {
    const raw = localStorage.getItem(KEY);
    current = raw ? JSON.parse(raw) : [];
  } catch {
    // Unreadable (blocked storage, corrupt JSON): refuse the write rather
    // than overwrite a list we couldn't see.
    return false;
  }
  const next = change(current);
  localStorage.setItem(KEY, JSON.stringify(next));
  store.setEntries(next);
  return true;
}

const save = (record) => mutate((list) => [record, ...list.filter((r) => r.id !== record.id)]);
const remove = (id) => mutate((list) => list.filter((r) => r.id !== id));

localStorage operations are synchronous, and in practice a read-then-write inside one task doesn't interleave with another tab's write, so this closes the window that matters. (If you need real transactions across tabs, use IndexedDB or the Web Locks API.)

Two more pieces keep the view honest:

  • Listen for the storage event. It fires in every other same-origin tab when one tab writes, so each tab can re-read and update its list. Keep unchanged records as the same objects, so the UI doesn't re-render everything for one change.
  • Re-read on pageshow with persisted set. A page restored from the back/forward cache missed every storage event fired while it was frozen.

There's also a subtle case. If another tab deletes a draft that this tab has open in its editor, the record disappears from the list, but this tab may still be using it. Images in that draft live in IndexedDB, which is also shared between tabs. Those entries stay in a "deleted elsewhere" set for the lifetime of the page, so the image cleanup won't remove files the open editor still shows.

A test now replays the incident exactly (two stores sharing one storage, an old tab saving last) and fails on the old code.

Trap: getItem can throw

A related bug took the whole app down for a different visitor. localStorage.getItem doesn't just return null when storage is unavailable. When a user has blocked site data, merely accessing window.localStorage or calling getItem throws a SecurityError. DWEEB read a "have we shown the welcome gallery?" flag inside a component's state initializer, so the throw escaped rendering and landed on the error screen, over a browser privacy setting. Now every storage access is wrapped, and an unreadable flag reads as "never", which is the safe first-visit answer.

Two IndexedDB traps from the same feature

Images people add to a draft are stored as blobs in IndexedDB, and a cleanup pass deletes blobs that no draft references any more. Both of these bit me there.

IDBCursor.delete() throws on a key cursor

To find orphans without loading every image into memory, the cleanup iterated with openKeyCursor(), which yields keys only. Calling cursor.delete() on a key cursor throws InvalidStateError. The spec only allows it on a value cursor. Worse, an exception thrown inside a transaction's event handler aborts the whole transaction. The same transaction was also loading the user's live images, so one orphan both produced a crash report and silently dropped every image in the open draft. The fix is to issue a separate store.delete(key) request per orphan, and to call preventDefault() on each request's error event so a single failed delete can't abort the rest.

const request = store.openKeyCursor();
request.onsuccess = () => {
  const cursor = request.result;
  if (!cursor) return;
  if (!referenced.has(cursor.key)) {
    const del = store.delete(cursor.key);       // not cursor.delete()
    del.onerror = (event) => event.preventDefault(); // don't abort the transaction
  }
  cursor.continue();
};

For tests, the fake-indexeddb package enforces this spec restriction, so the bug reproduces in a unit test without a browser.

Cleanup judged by one tab is wrong for all of them

Each tab decided what counted as an orphan from its own editor and its own view of the saved drafts. Delete a draft in one tab, and that tab's cleanup would remove the images another tab had just loaded from it. They'd come back as "missing" after a reload. Now loading and pruning are separate steps. Loading always happens. Pruning stored bytes only happens when a quick BroadcastChannel ping finds no other open tab of the app. Memory is still freed immediately in each tab. Disk is only cleaned by a tab that knows it's alone.

Rules I now follow for browser storage

  • Shared storage plus per-tab memory means memory is a cache. Never write it back as the source of truth.
  • Mutate by reading, changing one thing and writing. Refuse to write over data you couldn't read.
  • Follow other tabs with the storage event and pageshow.
  • Treat every storage access as something that can throw.
  • Before deleting shared data, ask whether another tab could still be using it.