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:
- Explain what
localStorageis, what it is good for and its limits. - Convert data to and from JSON.
- Save habits on every change and load them on page start.
- Make loading defensive: corrupted, old-format or blocked storage must not crash the app.
- Inspect and edit saved data in browser DevTools.
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:
- It stores strings only. Arrays and objects must go through JSON.
- Data is per site (origin) and per browser on one device. Your phone and laptop do not share it.
- It survives refreshes and restarts, but users can clear it, and some private-browsing modes clear it when the window closes or block it.
- It is small (a few megabytes) and synchronous. Fine for habits, not for photos.
- Anything in it is readable by any script on your page. Never store secrets there.
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:
storage.js:serialize,deserialize,loadHabits(storage),saveHabits(storage, habits). The storage object is passed in, so tests can use a fake.app.js: passeswindow.localStoragein.
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
- Start the server and open the app.
- Add two habits and tick one.
- Refresh. Both habits and the tick should still be there.
- Close the tab, open it again. Still there.
Step 4: Look inside storage with DevTools
Open DevTools (F12, or Cmd+Option+I on macOS):
- Chrome or Edge: Application tab, Storage, Local storage,
http://localhost:8000. - Firefox: Storage tab, Local Storage.
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.
- In DevTools, edit the value to
{not jsonand refresh. The app should show an empty list, not a blank page or a console error that stops everything. - Set the value to
[{"id":"x","name":"Old format","done":["2026-12-01"]}](a bare array) and refresh. The habit should appear. - 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. - 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
storage.jsnever lets an exception escape from loading.- The storage object is a parameter, not a hard-coded
window.localStorageinside the functions. - Saved JSON has a
versionfield. - The app keeps working with corrupted data, old-format data and blocked storage.
- A user-visible message appears when saving fails, instead of silently losing data.
Checklist
- Habits survive refresh and tab close.
- I found and read the saved JSON in DevTools.
- Invalid JSON in storage does not crash the app.
- Old bare-array data still loads.
- Invalid entries are dropped, valid ones kept.
- Save failures show a message.
- Committed.
Mini-quiz
- What type of value does
localStoragestore? - What happens if you call
JSON.parse("{not json")? - Why include a
versionin saved data? - Why pass the storage object into
loadHabitsinstead of usinglocalStoragedirectly inside it? - Your friend opens your app on their phone. Do they see your habits? Why?
- 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
- Add an “Export” button that downloads the habits as a
.jsonfile (hint: ask aboutBlobandURL.createObjectURL). Plan first. - 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. - Break-test import with a broken file, like you did in Step 5.
- Commit each feature separately.