Skip to the content.

Lesson 7: Save Data with localStorage

Course home Previous: Lesson 6 Next: Lesson 8

Time: about 60 minutes.

Goals

By the end of this lesson you will be able to:

Concepts

localStorage in one minute

localStorage is a small key-value store built into every browser, part of the Web Storage API.

localStorage.setItem("greeting", "hello");
localStorage.getItem("greeting");   // "hello"
localStorage.getItem("missing");    // null
localStorage.removeItem("greeting");

Facts to remember:

JSON

const text = JSON.stringify({ name: "Read", done: [] });
// '{"name":"Read","done":[]}'
const back = JSON.parse(text);
// { name: "Read", done: [] }

JSON.parse throws an error if the text is not valid JSON. That is the most common way a storage-based app breaks.

Defensive loading

Ask “what could be in storage?” Not just what your current code writes:

What might be there Cause What the app should do
Nothing (null) First visit Start with an empty list
Valid data in the current format Normal Load it
Data in an older format You changed the app Convert it if you can
Invalid JSON Manual editing, a bug, a browser extension Start empty, do not crash
Valid JSON with wrong shapes (missing names, bad dates, duplicate ids) Old bugs, manual editing Keep the good entries, drop the bad
Storage throws on access Blocked cookies or site data, some privacy modes Run without saving and tell the user
Save throws Storage full Keep working and tell the user

Versioned save format

Save as {"version": 1, "habits": [...]} instead of a bare array. When you change the format later, the version number tells your loader how to read old saves.

Keep storage at the edges

The reference splits it:

Walkthrough

Step 1: Plan

Read AGENTS.md, habits.js and app.js. I want habits to survive a refresh
using localStorage. Plan a new storage.js module with:
- STORAGE_KEY = "habit-tracker:v1"
- serialize(habits) -> JSON text of { version: 1, habits }
- deserialize(text) -> a clean habit array. It must never throw: null,
  empty, invalid JSON, wrong shapes all give [] or only the valid habits.
  Also accept a bare array (an early draft format). Drop habits without a
  name or id, drop invalid dates, sort and de-duplicate done days, and
  drop duplicate ids.
- loadHabits(storage) and saveHabits(storage, habits) that take the storage
  object as a parameter and catch errors; saveHabits returns true or false.
In app.js: load on start, save after every change, and if saving fails show
a short message in a role="status" element.
Tell me every failure case you are handling before writing code.

Compare the agent’s failure list with the table above. Add anything it missed.

Step 2: Build and commit

Approve the plan. After the change, check the diff:

git diff

You should see a new storage.js, small changes in app.js and maybe a new <p id="status" role="status"> in index.html. Nothing else.

Step 3: Test the happy path

  1. Start the server and open the app.
  2. Add two habits and tick one.
  3. Refresh. Both habits and the tick should still be there.
  4. Close the tab, open it again. Still there.

Step 4: Look inside storage with DevTools

Open DevTools (F12, or Cmd+Option+I on macOS):

Find the habit-tracker:v1 key. Its value is your JSON. Read it: can you find the habit names and the ticked day?

Step 5: Break it on purpose

This is where you find out if loading is really defensive.

  1. In DevTools, edit the value to {not json and refresh. The app should show an empty list, not a blank page or a console error that stops everything.
  2. Set the value to [{"id":"x","name":"Old format","done":["2026-12-01"]}] (a bare array) and refresh. The habit should appear.
  3. Set it to {"version":1,"habits":[{"id":"a","name":" ","done":[]},{"id":"b","name":"Walk","done":["not-a-date","2026-12-01"]}]} and refresh. Only “Walk” should appear, with one ticked day.
  4. Add a habit now; the storage value should be rewritten in the clean format.

If any of these break the app, give the agent the evidence:

Bug: if localStorage contains {not json the page stops working.
Expected: empty list, app still usable.
Console shows: [paste the exact error].
Find the cause in storage.js and fix it without changing the save format.

Step 6: Private and blocked storage

Open the app in a private or incognito window. It should still work in that window. If your browser blocks site data in private mode, the status message should appear. Either way, nothing should crash.

Step 7: Commit

git add storage.js app.js index.html
git commit -m "Save habits to localStorage with defensive loading"

What good output looks like

Checklist

Mini-quiz

  1. What type of value does localStorage store?
  2. What happens if you call JSON.parse("{not json")?
  3. Why include a version in saved data?
  4. Why pass the storage object into loadHabits instead of using localStorage directly inside it?
  5. Your friend opens your app on their phone. Do they see your habits? Why?
  6. Should you store an API key in localStorage?
Answers 1. Strings. 2. It throws a `SyntaxError`. Without a `try`/`catch`, that can stop your app's startup code. 3. So future versions of the app can recognise and convert older save formats. 4. So the function can be tested in Node with a fake storage object, and so the app can handle storage being unavailable. 5. No. localStorage belongs to one browser on one device for one site. Their phone has its own empty storage. 6. No. Any script on the page can read localStorage, and front-end code is public anyway. Secrets belong on a server.

Assignment

  1. Add an “Export” button that downloads the habits as a .json file (hint: ask about Blob and URL.createObjectURL). Plan first.
  2. Add an “Import” option that reads such a file and runs it through deserialize, so bad files cannot break the app. Ask the agent to confirm before replacing existing habits.
  3. Break-test import with a broken file, like you did in Step 5.
  4. Commit each feature separately.

Next: Lesson 8: Review AI code like an editor