Contents Lesson 2 of 19

13 min read · professional

Move persistence off the browser

By the end of this lesson you will have a document store on your server with a version on every document, your saved screens read from it with this browser's copy as the fallback, a test that asks for another user's document and gets a 404, and step 1 of the migration committed on its own.

Your notes, sort order, saved screens and shortlist sit in localStorage, and that was deliberate: it protected Build Your First Tool's ten-minute first win and needed no backend. That decision has now expired, and this lesson is about migrating rather than regretting.

What localStorage actually promised

It promised this browser, this profile, this origin, until something clears it. That was fine for one list on one laptop. Four things break it once you have a cockpit:

  • One device. Your layout does not follow you to another machine, and a dashboard is exactly the thing you want on the big screen and the small one.
  • Silently evictable. Private windows, storage pressure and "clear site data" all take it, with no event you can catch.
  • No history. A bad edit is permanent; there is no version of yesterday's layout.
  • Nothing else can read it. An alert that fires while the tab is closed needs your rules somewhere a server can see them, which is unit 3.

Migrate, do not switch

The wrong move is deleting the localStorage code and shipping. Your own data is in there, and so is anyone else's who used your tool.

The right shape is three steps, in this order:

  1. Read from server, fall back to local. Ship this alone and nothing changes for anyone.
  2. On first successful server read, upload whatever is local and mark it migrated. One flag, written after the upload succeeds, never before.
  3. Remove the fallback once you have seen the migration work on your own data on two devices.

Each step is separately revertible, which is the property that matters. This is exactly the small-diffs discipline from Build Your First Tool applied to something that can lose your data.

The shape on the server

Keep it boring. One row per user per document, the document as JSON, and a version integer:

user_id | key       | version | payload           | updated_at
--------|-----------|---------|-------------------|-----------
1       | watchlist | 3       | {"symbols":[...]} | ...
1       | layout    | 7       | {"panels":[...]}  | ...

The version column is not decoration. Two tabs open on the same dashboard will both write, and without a version the second write silently destroys the first. Send the version you read, reject the write if it has moved, and tell the user their other tab is ahead. That is fifteen lines and it is the difference between a tool you trust and one that eats your work.

Where the key still is not

Nothing changes about secrets. The server now stores your documents and holds the API key, which means the proxy from Build Your First Tool and this store are the same server — one deployment, one environment file, one CI scan already watching it.

What is new is that you now hold someone else's data, even if that someone is only you. Every request must be scoped by the authenticated user, and a query without a user_id filter is the whole vulnerability in one line. Add a test that asks for another user's document and expects a 404.

Try it now

Ship step 1 only — read from server, fall back to local — and use it for a day before writing step 2. If the fallback ever fires, you have learned something about your own reliability that a migration done in one commit would have hidden.

The prompt

In the starter the watchlist itself is a file and a cookie; what lives in localStorage is the saved screens, the shortlist and the notes, all through src/lib/stored.ts. This prompt moves the saved screens. Moving the shortlist and the notes the same way, a commit each, is optional practice: our reference does it, and nothing later in the course depends on it. The sort order stays where it is, because it is panel-local.

Mock mode on, plan mode on, and paste:

Plan step 1 of moving the saved screens off the browser, and only step 1.
Add src/lib/store.ts: documents keyed by user and key, each with a
version integer, a payload and updatedAt, one table docs in SQLite
through Node's built-in node:sqlite, in .data/app.db, which git
ignores; the tests use ":memory:". The columns of docs are exactly
user_id, key, version, payload and updated_at. node:sqlite needs
Node 22.13 or newer, so raise engines in package.json to
">=22.13.0" with no upper limit, raise @types/node to ^22 to match,
run npm install so the lockfile follows, and add no type shim of
your own. putDoc takes the version the caller
read and refuses the write if it has moved, in one conditional UPDATE,
so two writes arriving together cannot both pass. Every function takes
the user first, and
src/lib/user.ts is the one place the current user comes from; until
there is a sign-in it returns the number 1, one owner. Add the
route src/app/api/store/[key]/route.ts: GET is 404 for a missing
document, PUT is 409 on a stale version, and only the keys I list exist; for now
the only key is screens-v1.
The saved-screens component reads the route and falls back to
localStorage only when the server has nothing; writes go to the server
and, until the fallback is removed, to localStorage too. Write
tests/store.test.ts first: a stale version is refused, and another
user's document is a 404. No upstream request. Run npm test, typecheck,
lint and check:leak, and show me the diff before committing.

A good answer adds src/lib/store.ts, src/lib/user.ts, the route and its test, changes the saved-screens component, and adds .data/ to .gitignore. node:sqlite runs without a flag from Node 22.13, which is why the prompt asks for engines and @types/node to be raised: without them the typecheck cannot find the module and the README keeps promising Node 20. Nothing else is added to the dependencies. Until there is a sign-in, every request belongs to the one owner user.ts returns; a second user only exists in the test. No upload step runs yet: that is step 2, after a day of use. But a save sends the list you see, so your first save after a page that fell back to this browser writes that whole local list to the server.

Check it yourself

  1. The two new tests were red before the store existed and are green now, beside the starter's own.
  2. Save a screen, then read the store from the terminal: node -e "console.log(new (require('node:sqlite').DatabaseSync)('.data/app.db').prepare('SELECT user_id, key, version FROM docs').all())" prints one row, with user_id 1 and a version. If the command says no such column, the table was built with other column names: ask the agent to rename them to the five in the prompt.
  3. Open the screen page in a private window, whose storage is empty: the saved screen is there, so it came from the server.
  4. curl -i localhost:3000/api/store/anything-else answers 404: only the keys you listed exist.
  5. git status does not list .data/, so your documents are not about to be committed.
  6. npm run typecheck is green and package.json now says >=22.13.0 under engines.

On a first load with an empty store the browser console shows a red 404 for the screens document. That is the server's honest answer "nothing saved yet", and the component then falls back to this browser; it is not a fault. Writes go to both places until the fallback is removed because the fallback is the safety net: if the server write fails you still have the copy in this browser.

Compare with ours
// src/lib/store.ts: one row per user per document, and the version is not decoration
const update = db.prepare(
  "UPDATE docs SET version = version + 1, payload = ?, updated_at = ? " +
  "WHERE user_id = ? AND key = ? AND version = ?",   // compare and set, one statement
);

export function putDoc(user: number, key: DocKey, payload: unknown, version: number) {
  const now = new Date().toISOString();
  const text = JSON.stringify(payload);
  const changed = version === 0
    ? insert.run(user, key, text, now).changes        // INSERT ... ON CONFLICT DO NOTHING
    : update.run(text, now, user, key, version).changes;
  return changed === 1
    ? { conflict: false as const, version: version + 1 }
    : { conflict: true as const, current: getDoc(user, key) };   // the other tab is ahead: say so
}

The check and the write are one statement. Read a file, await, write it back, and two writes that arrive together both pass the check, and the second silently replaces the first. getDoc selects WHERE user_id = ? AND key = ? and the route turns its null into a 404. Ours moves the saved screens, the shortlist and the notes in a commit each, and keeps the sort order in this browser. Our user.ts reads the owner from the optional sign-in's cookie; yours returns 1, which is all this course needs. The full state at the end of this unit is on the starter's branch ref/build-a-dashboard/u1.

Checkpoint

npm test && npm run typecheck
git status          # the files you expect, and no .env file or .data/
git add -A
git commit -m "Saved screens read from the server, this browser as fallback (step 1 of 3)"

Then answer this lesson's questions.