Skip to content
Tutorials Center
My learning

Topics

Lesson 140 of 156 ยท Projects

Project: Notes App with Storage

Build a notes app with create, edit, pin, search and delete, saved in localStorage with a safe wrapper, versioned data, JSON export and validated import.

A notes app is the best first project for learning persistence. Everything feels simple until you ask the awkward questions: what happens when the saved data is corrupted? When storage is full or switched off? When you change the data format next month and old notes are still in people's browsers? When the same app is open in two tabs?

In this project you build a notes app with the full set of CRUD actions (create, read, update, delete), plus pinning, live search, autosave, export and import as JSON, and syncing between tabs. You will write the data logic first as pure functions with a swappable storage backend, then wrap a user interface around it.

It builds on localStorage and sessionStorage, JSON, Error Handling and Bubbling, Capturing and Delegation.

Storage is blocked in these editors. The previews run in a sandbox with no localStorage, so the app uses a wrapper that tries real storage and falls back to memory when it throws. On your own page the same code saves for real. Notes you write here vanish when you reload the lesson, and the app tells you so.

The data design

Decide what a note is before writing any code. We store:

JavaScript
{ id: "k3j9x2", title: "Groceries", body: "milk, eggs", pinned: false, createdAt: 1730000000000, updatedAt: 1730000050000 }
  • id is a string that never changes, so a note can be found even after the list is sorted or filtered.
  • Timestamps are numbers (milliseconds since 1970), which sort and compare easily and survive JSON.
  • All notes live under one storage key, wrapped in an envelope with a version: { "version": 1, "notes": [...] }. When the format changes, version 2 code can recognise old data and migrate it, instead of crashing on it.

Step 1: A storage layer you can test

localStorage has two awkward properties: it is synchronous and it only stores strings. So a small store object wraps it. The trick for testability is to accept the backend as a parameter. Anything with getItem() and setItem() works, so tests, and these sandboxed editors, can use a plain in-memory backend.

The store's job is to never throw at the rest of the app:

  • load() returns [] when nothing is saved, when the JSON is broken, or when the shape is wrong.
  • save() returns true or false, so the interface can warn when storage is full.
JS Step 1: Store and note functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice what the updates do: updateNote() spreads the old note and overlays the changes, so it returns a new array and leaves the old one untouched. That makes "what changed?" easy to reason about, and it is the same shape React and other libraries expect. Each storage call is wrapped in try/catch, so a corrupted value costs the user their saved notes, but never takes down the page.

Never trust data you read back from storage. Users can edit it in DevTools, other scripts on the same origin can overwrite it, and old versions of your own app may have saved a different shape. Validate on the way in, exactly as you would validate a form.

Step 2: Export and import with validation

Browser storage belongs to one browser on one device. Clearing site data erases it, and nothing syncs. An export button that produces JSON gives people a backup, and an import that reads it back gives them portability. Import is the dangerous direction: the text may be wrong, from a future version, or hand-edited. So we validate every field and skip bad entries instead of aborting.

Merging is the other decision. If an imported note has an id we already have, which wins? A sensible rule is newest updatedAt wins, which never silently loses recent work.

JS Step 2: Validate and merge imported notes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Three of the six imported entries are valid and three are skipped: one with a numeric id, one that is not an object, and note d, which has no finite updatedAt. Of the valid three, one is new (c), one replaces an older copy (b), and one loses to the newer version we already have (a). Because validation produces fresh, clean objects with only the known fields, extra fields in an imported file can never sneak into your data. Truncating title and body also stops a huge file from filling the storage quota.

Step 3: The interface

Now the screen: a list on the left (with search and a "New note" button), an editor on the right, and a collapsible export/import panel. The wiring follows the same pattern as every project in this series:

  • State is three values: notes, selectedId and query. Everything on screen comes from them.
  • renderList() rebuilds the list from sortNotes(searchNotes(...)). It uses textContent for every note title and snippet, never innerHTML: note text is user input, and putting it in HTML would let a note run scripts (see XSS).
  • Autosave is debounced. Typing updates the note in memory on each keystroke, but writing to storage waits until you pause for 300 ms. A "Saved" status line confirms it.
  • Delete takes two clicks. The first changes the button to "Click again to delete" for three seconds. That is friendlier than confirm(), which is blocked in sandboxed iframes, annoying everywhere, and impossible to style.
  • The storage event fires in other tabs when one tab changes localStorage, so each tab can reload the notes and stay in sync. It never fires in the tab that made the change.
Step 3: The notes app

Create a note, type into it, pin it, search for a word from its body, and press Delete twice. Then open Export and import, press Export, edit the JSON (change a title, add a new note object) and press Import: the merge rule applies, so only entries that are newer or new are applied.

Some details worth studying:

  • replaceChildren() clears a list in one call before it is rebuilt.
  • Search runs on input, not keyup, so paste, cut and mobile keyboards all work.
  • aria-current marks the open note in the list for screen readers, and the same attribute styles it in CSS.
  • changeSelected() is the one place that edits a note. Typing, pinning and (conceptually) anything new all go through it, so updatedAt, rendering and saving cannot be forgotten.
  • No innerHTML anywhere. Titles and bodies are only ever assigned through textContent or .value. Try pasting <img src=x onerror=alert(1)> as a title; it displays as plain text.

Downloading the export as a file

The sandbox doesn't allow downloads, so the demo shows the JSON in a box. On your own page, a download is a few lines with a Blob:

JavaScript
function downloadJson(notes) {
  const blob = new Blob([JSON.stringify({ version: 1, notes }, null, 2)], { type: "application/json" });
  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = "notes-backup.json";
  link.click();
  URL.revokeObjectURL(link.href); // free the temporary URL
}

For import from a file, add <input type="file" accept="application/json"> and read it with await file.text(), then pass the text to the same validation code.

Ideas to extend it

  • Tags and filters. Add a tags array to each note, validate it in cleanNote(), and add a tag filter next to the search box.
  • Undo delete. Keep the removed note for ten seconds and show an "Undo" toast, as described in the UI widgets ideas.
  • IndexedDB. When notes grow beyond roughly 5 MB, localStorage is not enough. Move the store behind the same load()/save() interface and nothing else changes.
  • Markdown preview. Render the body safely by escaping first, then converting a small Markdown subset.
  • Server sync. Send updatedAt with each note, and reuse the "newest wins" merge to reconcile with a server.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the store accept a backend object instead of calling localStorage directly?

    Passing the backend in is dependency injection. The same logic runs against localStorage, an in-memory Map or a fake that throws, which makes it testable and lets the app degrade gracefully.
  2. 2. Why is a version number stored with the notes?

    Data saved today may be read by code written next year. A version number lets that code detect the format and upgrade it or reject it safely.
  3. 3. Which approach should the app use to display a note's title in the list?

    Note text is user input. textContent shows it as plain text; innerHTML would parse it as HTML and could run attacker-supplied code.
  4. 4. When does the storage event fire?

    The event is delivered to other documents on the same origin, which is exactly what keeping several tabs in sync needs. The tab that made the change already knows.
  5. 5. When importing notes with the same id as an existing note, which merge rule does the lesson use?

    Choosing by updatedAt never throws away the most recent edit, whichever side it came from, and it is safe to re-import the same file repeatedly.

Summary

  • Design the data shape first: stable ids, numeric timestamps, and a versioned envelope under one storage key.
  • Wrap storage in a small store with load() and save() that never throw, and accept the backend as a parameter so you can test it and fall back to memory.
  • Keep note functions pure: they take an array and return a new array.
  • Validate everything read from storage or an import file, building fresh objects from known fields and skipping bad entries.
  • Autosave with a debounce, confirm destructive actions without confirm(), and never put user text into innerHTML.
  • Use the storage event to sync tabs, Blob with URL.createObjectURL() for downloads, and "newest updatedAt wins" for merges.

Next: Project: Text Editor and Word Counter.