A scoreboard that survives refresh, and three real localStorage traps
The scoreboard is pure client state, but users refresh by accident, and mobile OSes kill background tabs. Without persistence, a 7:5 game vanishes on refresh. My first instinct was "one line of localStorage, done." Then
The scoreboard is pure client state, but users refresh by accident, and mobile OSes kill background tabs. Without persistence, a 7:5 game vanishes on refresh.
My first instinct was "one line of localStorage, done." Then I found three traps:
Trap 1: Safari private mode
localStorage.setItem throws QuotaExceededError in private mode. Not because the quota is full — because the mode disables storage entirely. You must try/catch:
function save(state) {
try {
localStorage.setItem('swg:score', JSON.stringify(state));
return true;
} catch {
return false; // private mode or quota full; keep in-memory state, just don't persist
}
}
Trap 2: Multiple tabs overwriting each other
A user opens two tabs, plays two games, the later write overwrites the earlier. The storage event helps, but the simpler approach is a game ID: every "new game" generates an ID, and reading checks that IDs match:
const gameId = crypto.randomUUID();
save({ gameId, a: 0, b: 0 });
// on read
const raw = localStorage.getItem('swg:score');
if (raw) {
const s = JSON.parse(raw);
if (s.gameId === expectedId) restore(s);
}
Trap 3: Old data formats
I changed the scoreboard data structure once. Long-time users had old-format data in storage, and the fields read back as undefined. A version field fixes it:
{ version: 2, gameId, a, b }
Discard on version mismatch.
These are real problems, regardless of whether this site uses them. I didn't pull in a state library because these persistence issues fit in tens of lines, and a dependency would blur the boundary.
What I'd tell you not to do
Don't use sessionStorage hoping "one game, then auto-clear." Tab crash recovery and mobile app switching make sessionStorage's behavior more complex than you expect. An explicit gameId boundary is more predictable than relying on storage lifecycle.
The scoreboard is at sketchwordgen.com — start a game, refresh halfway, see what survives.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.