Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 30 min · revision 3

Lab: An Offline-First Notes App with Live Updates

Build and verify a notes app that renders from IndexedDB first, syncs through a notes API, receives other sessions' edits over Server-Sent Events, precaches its shell with an update prompt, and parses a 100,000-note import in a worker.

Contentsand lesson path

What you will learn

  • Choose between cookies, Web Storage, IndexedDB and the Cache API by capacity, persistence, synchronous or asynchronous access and exposure to scripts, and persist structured app data in IndexedDB.
  • Move CPU-heavy work such as parsing or filtering a large dataset into a Web Worker with message passing, and show the gain in input responsiveness in a Performance trace.
  • Deliver live and streamed data to the UI with polling, Server-Sent Events, WebSockets or a streamed fetch body (for example LLM output relayed by your own server so API keys never reach the browser), justifying the choice and handling reconnection and cancellation.
  • Make an app installable and usable offline with a web app manifest and a service worker (lifecycle, update prompt, cache strategy chosen per request type), and state when a PWA falls short and a native, cross-platform or desktop app is warranted.

Prerequisites: Async JavaScript & Fetch

01. Goal and setup

This lab assembles the four previous lessons into one working app: notes stored in IndexedDB and rendered before the network answers, a small Node server for notes and live updates, a service worker that precaches the shell behind an "update available" prompt, and a bulk import parsed in a Web Worker. Every step ends with output you can reproduce; the expected outputs shown here were produced by running this exact code in Chromium against this exact server.

You need: Node 22 or later (node --version) and any current Chromium- or Firefox-based browser. No packages: the server uses only Node built-ins, and the front end is plain JavaScript modules. Create a folder notes-app with this layout and the files below inside it:

Project layout
notes-app/
├── server.mjs             static files, notes API, SSE feed, import file
├── public/                everything the browser loads
│   ├── index.html         the shell (a labelled form, a live status, a list)
│   ├── styles.css         a few layout rules
│   ├── app.js             page logic, added step by step
│   ├── db.js              IndexedDB wrapper
│   ├── import-worker.js   parses the archive off the main thread
│   ├── sw.js              the service worker
│   ├── manifest.webmanifest
│   ├── icon-192.png
│   └── icon-512.png

The two PNG icons can be any real 192 px and 512 px images; they exist so the manifest satisfies install criteria. The order of the steps is the order the pieces matter in: data first, then the UI on top of it, then offline, then live, then the import. Each step is small enough to check before moving on.

02. Step 1: the server — static files, an API, an SSE feed

JavaScript · server.mjs
// server.mjs — serves the notes app, its API, an SSE feed and a large import file.
import { createServer } from 'node:http';
import { readFileSync, existsSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const root = join(dirname(fileURLToPath(import.meta.url)), 'public');
const port = 4321;

const notes = [
  { id: 1, text: 'Outline the chapter', done: false },
  { id: 2, text: 'Book train tickets', done: false },
];
let nextId = 3;
const feedClients = new Set();
const broadcast = (change) => {
  for (const res of feedClients) res.write(`data: ${JSON.stringify(change)}\n\n`);
};
let importBody = null;

const types = {
  '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css',
  '.webmanifest': 'application/manifest+json', '.png': 'image/png',
};

createServer((req, res) => {
  const { pathname } = new URL(req.url, `http://localhost:${port}`);

  if (pathname === '/api/notes' && req.method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    return res.end(JSON.stringify(notes));
  }
  if (pathname === '/api/notes' && req.method === 'POST') {
    let body = '';
    req.on('data', (chunk) => { body += chunk; });
    req.on('end', () => {
      const { text, from } = JSON.parse(body); // from: the tab that sent it
      const note = { id: nextId++, text, done: false };
      notes.push(note);
      broadcast({ kind: 'added', note, from });
      res.writeHead(201, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify(note));
    });
    return;
  }
  if (pathname === '/api/import') {
    if (!importBody) {
      const rows = Array.from({ length: 100000 }, (_, i) => ({
        id: i + 100000, text: `Archive note ${i}: file, sort, keep or delete.`,
        done: true,
      }));
      importBody = JSON.stringify(rows);
    }
    res.writeHead(200, { 'Content-Type': 'application/json' });
    return res.end(importBody);
  }
  if (pathname === '/feed') {
    res.writeHead(200, {
      'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache',
      Connection: 'keep-alive',
    });
    res.write('retry: 2000\n\n');
    feedClients.add(res);
    req.on('close', () => feedClients.delete(res));
    return;
  }
  const file = join(root, pathname === '/' ? 'index.html' : pathname.slice(1));
  if (existsSync(file)) {
    const type = types[file.slice(file.lastIndexOf('.'))] ??
      'application/octet-stream';
    res.writeHead(200, { 'Content-Type': `${type}; charset=utf-8` });
    return res.end(readFileSync(file));
  }
  res.writeHead(404);
  res.end('not found');
}).listen(port, () => console.log(`notes app on http://localhost:${port}`));
Terminal
mkdir -p notes-app/public && cd notes-app
# create server.mjs here; the public/ files follow in later steps
node server.mjs &
curl -s http://localhost:4321/api/notes
Expected output (curl prints the JSON on one line; wrapped here for width)
notes app on http://localhost:4321
[{"id":1,"text":"Outline the chapter","done":false},
{"id":2,"text":"Book train tickets","done":false}]

The server is deliberately thin: one in-memory array as the source of truth, a POST that assigns ids and broadcasts a change, an SSE route that keeps a set of open responses, and an import route that generates a 100,000-row JSON file on first request. Put the front-end files under public/ — the server maps / to public/index.html and serves everything else from that folder by name.

03. Step 2: the IndexedDB layer

JavaScript · public/db.js
// db.js — a small promise wrapper around IndexedDB
const DB_NAME = 'notes-app';
const STORE = 'notes';

export function openDb() {
  return new Promise((resolve, reject) => {
    const open = indexedDB.open(DB_NAME, 1);
    open.onupgradeneeded = () => {
      open.result.createObjectStore(STORE, { keyPath: 'id' });
    };
    open.onsuccess = () => resolve(open.result);
    open.onerror = () => reject(open.error);
  });
}

function asPromise(request) {
  return new Promise((resolve, reject) => {
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
}

/** Reads at most `limit` notes, in key order: the page never draws more. */
export async function listNotes(db, limit = 100) {
  return asPromise(db.transaction(STORE).objectStore(STORE).getAll(null, limit));
}

export async function countNotes(db) {
  return asPromise(db.transaction(STORE).objectStore(STORE).count());
}

/** Puts every note in one transaction; resolves with how many it stored. */
export function saveNotes(db, incoming) {
  return new Promise((resolve, reject) => {
    const tx = db.transaction(STORE, 'readwrite');
    const store = tx.objectStore(STORE);
    for (const note of incoming) store.put(note);
    tx.oncomplete = () => resolve(incoming.length);
    tx.onerror = () => reject(tx.error);
  });
}

/** Used on sign-out: the next account must not see this one's notes. */
export function clearNotes(db) {
  return new Promise((resolve, reject) => {
    const tx = db.transaction(STORE, 'readwrite');
    tx.objectStore(STORE).clear();
    tx.oncomplete = () => resolve('cleared');
    tx.onerror = () => reject(tx.error);
  });
}
JavaScript · a quick check from any page on localhost:4321
const { openDb, listNotes, saveNotes, clearNotes } = await import('/db.js');
const db = await openDb();
console.log('before:', (await listNotes(db)).length, 'notes');
await saveNotes(db, [{ id: 99, text: 'smoke test', done: false }]);
console.log('after:', (await listNotes(db)).length, 'notes');
await clearNotes(db); // undo the smoke test; the next load re-syncs
Expected output (browser console, devtools tab of the app)
before: 0 notes
after: 1 notes

The wrapper exists so the rest of the app reads like awaits and arrays, not like event handlers. Three details do the heavy lifting later: listNotes reads a bounded page of records, never the whole store; saveNotes puts many records in one transaction, which is what makes the 100,000-row import cheap; and clearNotes is the sign-out story from the storage lesson — the next account on this browser must not inherit this one's records.

04. Step 3: the shell, and sync the server into IndexedDB

HTML · public/index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Offline Notes</title>
  <link rel="manifest" href="/manifest.webmanifest">
  <link rel="stylesheet" href="/styles.css">
</head>
<body>
  <main>
    <h1>Offline Notes</h1>
    <form id="add-form">
      <label for="note-text">New note</label>
      <input id="note-text" name="text" type="text" required autocomplete="off">
      <button type="submit">Add note</button>
    </form>
    <p id="status" role="status" aria-live="polite">Loading&hellip;</p>
    <p>
      <button id="update" type="button" hidden>Reload to update</button>
      <button id="import" type="button">Import archive</button>
    </p>
    <ul id="notes"></ul>
  </main>
  <script type="module" src="/app.js"></script>
</body>
</html>
CSS · public/styles.css
body { font-family: system-ui, sans-serif; margin: 2rem auto; max-width: 40rem; }
form { display: flex; gap: 0.5rem; align-items: center; }
input { flex: 1; padding: 0.4rem; }
button { padding: 0.4rem 0.8rem; }
li { margin: 0.25rem 0; }
JavaScript · public/app.js (part 1 of 4)
import { openDb, listNotes, countNotes, saveNotes } from '/db.js';

const list = document.querySelector('#notes');
const status = document.querySelector('#status');
const form = document.querySelector('#add-form');
const input = document.querySelector('#note-text');
const updateButton = document.querySelector('#update');
const importButton = document.querySelector('#import');

/** Draws at most 100 notes; the status line reports the full count. */
function render(notes) {
  const shown = notes.slice(0, 100);
  list.replaceChildren(...shown.map((note) => {
    const item = document.createElement('li');
    item.dataset.id = note.id;
    item.textContent = note.text;
    return item;
  }));
}

function say(message) {
  // Write real changes only, so the live region does not repeat itself.
  if (status.textContent !== message) status.textContent = message;
}

/** Adds a line unless a note with this id is already on screen. */
function addLineOnce(note) {
  const onScreen = [...list.children].some((li) => li.dataset.id === String(note.id));
  if (onScreen) return false;
  const item = document.createElement('li');
  item.dataset.id = note.id;
  item.textContent = note.text;
  list.prepend(item);
  return true;
}

const state = { online: navigator.onLine, synced: 0 };
function refreshStatus() {
  if (!state.online) {
    say('Offline: showing notes stored on this device');
  } else if (state.synced) {
    say(`Live: ${state.synced} notes synced`);
  } else {
    say('Live: syncing notes…');
  }
}
window.addEventListener('online', () => { state.online = true; refreshStatus(); });
window.addEventListener('offline', () => { state.online = false; refreshStatus(); });

const db = await openDb();
render(await listNotes(db));
refreshStatus();

// 1. server data is the source of truth while online; it also lands in IndexedDB
async function syncFromServer() {
  try {
    const res = await fetch('/api/notes');
    if (!res.ok) return;
    const notes = await res.json();
    await saveNotes(db, notes);
    state.online = true;
    state.synced = notes.length;
    render(await listNotes(db));
  } catch {
    state.online = false;
  }
  refreshStatus();
}
await syncFromServer();
Expected output — the status line and the list on first load
Live: 2 notes synced
Outline the chapter
Book train tickets

The order is the offline-first idea in miniature: render from IndexedDB, then fetch. On a first visit the local render shows nothing and the fetch fills it; on later visits the local render is instant and the fetch only corrects it. The status line is a role="status" region with aria-live="polite", so screen readers hear connection changes without focus moving — the same standard the accessibility lessons hold the rest of the UI to: a real form with a labelled input, real buttons, a real list.

05. Step 4: live updates and a write that survives offline

JavaScript · public/app.js (part 2 of 4)
// 2. live updates from other sessions
// Sent with our POSTs and echoed by the server, so we can skip our own notes.
const TAB_ID = crypto.randomUUID();
const feed = new EventSource('/feed');
feed.onopen = () => {
  document.body.dataset.feed = 'open';
  if (state.synced) refreshStatus();
  else syncFromServer(); // the page loaded offline: sync now that we can
};
feed.onerror = () => {
  // Offline, EventSource retries every 2 s; report the drop once, so a message
  // such as "note stored" stays until the connection state really changes.
  if (document.body.dataset.feed === 'reconnecting') return;
  document.body.dataset.feed = 'reconnecting';
  refreshStatus();
};
feed.onmessage = (event) => {
  const change = JSON.parse(event.data);
  if (change.kind !== 'added' || change.from === TAB_ID) return; // ours: skip
  if (addLineOnce(change.note)) {
    say(`"${change.note.text}" added in another session`);
  }
};

// 3. adding a note: to the server when possible, queued in IndexedDB when not
form.addEventListener('submit', async (event) => {
  event.preventDefault();
  const text = input.value.trim();
  if (!text) return;
  input.value = '';
  try {
    const res = await fetch('/api/notes', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ text, from: TAB_ID }),
    });
    if (!res.ok) throw new Error(`status ${res.status}`);
    const note = await res.json();
    await saveNotes(db, [note]);
    state.synced += 1;
    addLineOnce(note);
    refreshStatus();
  } catch {
    const queued = { id: Date.now(), text, done: false, queued: true };
    await saveNotes(db, [queued]);
    addLineOnce(queued);
    say('Offline: note stored on this device, to send later');
  }
});
Expected output — two tabs open; the second adds "Call the bank"
// first tab, after you add "Water the plants":
Live: 3 notes synced
// first tab, no reload, after the second tab adds "Call the bank":
"Call the bank" added in another session   (and the note is at the top of the list)

The feed is the SSE client from the live-data lesson doing its job: the browser reconnects by itself, and the page only decides what to do with each change. The server broadcasts a note before it answers the POST, so a tab usually hears of its own note first. Each tab therefore sends a random TAB_ID, which the server echoes as from, and skips its own notes; notes from other sessions are announced by name, so two different notes in a row are two messages (a repeat of the same text is drawn but not announced: say() skips unchanged text). addLineOnce still deduplicates by id. The write path is the offline rule in action: the POST goes to the network, and when the network is gone the note lands in IndexedDB with queued: true — visible, honest, and explicitly not yet sent. Sending queued notes again later is replay, and replay needs re-authorisation; that is the stretch task at the end.

06. Step 5: the service worker — offline shell and update prompt

JavaScript · public/sw.js
// sw.js — precache the app shell; the notes API never enters the shared cache
const VERSION = 'notes-v1'; // bump this string to ship an update
// Only files that exist by now: every one must load, or the install fails.
const SHELL = ['/', '/app.js', '/db.js', '/styles.css'];

self.addEventListener('install', (event) => {
  event.waitUntil(caches.open(VERSION).then((cache) => cache.addAll(SHELL)));
});

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys()
      .then((keys) => Promise.all(keys.filter((k) => k !== VERSION)
        .map((k) => caches.delete(k))))
      .then(() => self.clients.claim()),
  );
});

self.addEventListener('message', (event) => {
  if (event.data === 'skip-waiting') self.skipWaiting();
});

self.addEventListener('fetch', (event) => {
  const url = new URL(event.request.url);
  const sameOriginGet = event.request.method === 'GET' &&
    url.origin === self.location.origin;
  const isShell = event.request.mode === 'navigate' ||
    SHELL.includes(url.pathname);
  if (!sameOriginGet || !isShell) return; // /api/* always reaches the network
  event.respondWith(
    caches.match(event.request).then((hit) => hit ?? fetch(event.request)),
  );
});
JavaScript · public/app.js (part 3 of 4)
// 4. service worker and the "update available" prompt
const registration = await navigator.serviceWorker.register('/sw.js');
let updateAccepted = false;
registration.addEventListener('updatefound', () => {
  const installing = registration.installing;
  installing?.addEventListener('statechange', () => {
    if (installing.state === 'installed' && navigator.serviceWorker.controller) {
      updateButton.hidden = false;
      say('A new version is ready');
    }
  });
});
updateButton.addEventListener('click', () => {
  updateAccepted = true;
  registration.waiting?.postMessage('skip-waiting');
});
navigator.serviceWorker.addEventListener('controllerchange', () => {
  // clients.claim() also fires this on the very first visit; reload only for
  // real updates
  if (updateAccepted) location.reload();
});
Expected output — DevTools set to Offline, then a new deploy
// network set to Offline, then reload:
Offline: showing notes stored on this device
// adding a note while offline:
Offline: note stored on this device, to send later
// network restored (the page loaded offline, so it syncs now):
Live: 4 notes synced
// after bumping VERSION and reloading, the status line shows:
A new version is ready          (the "Reload to update" button is visible)
// after clicking it, the page reloads into the new version:
Live: 4 notes synced

Test it like this: load the app once, then in DevTools set Network to Offline and reload. The shell comes from the precache, the notes come from IndexedDB, and the status line says so. Add a note: it queues, and the message stays put: offline, EventSource fires error on every retry, so onerror reports only the first and say() skips text already shown, sparing screen readers the repeats. Restore the network: the feed reconnects on its own (the body[data-feed] attribute makes the connection state visible), and because this page loaded offline and has synced nothing yet, the reconnect runs syncFromServer() once, so the status returns to Live: … notes synced, and the next change from another session arrives live. A page that had already synced does not refetch on reconnect, and updates broadcast while it was offline are not replayed, which is why a real client reconciles after reconnecting (the third stretch task). Then bump VERSION in sw.js and reload: the new worker installs and waits, the button appears, and clicking it trades control to the new version (it reloads only if updateAccepted, as clients.claim() fires controllerchange on a first visit too) — the update flow from the PWA lesson, with the user in charge.

07. Step 6: the manifest

JSON · public/manifest.webmanifest
{
  "name": "Offline Notes",
  "short_name": "Notes",
  "description": "Notes that work offline and update live.",
  "start_url": "/",
  "scope": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#0f172a",
  "icons": [
    { "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" },
    { "src": "/icon-512.png", "sizes": "512x512", "type": "image/png" }
  ]
}
Expected output (browser console)
// after fetching the manifest from the console:
fetch('/manifest.webmanifest').then((r) => r.json()).then(console.log)
> {name: 'Offline Notes', short_name: 'Notes', start_url: '/', ...}

With the manifest linked, a registered worker and two icons of the right sizes, the app meets Chromium's install criteria: the address bar offers an install action, and beforeinstallprompt lets a site offer its own button. That offer is browser UI, so an automated run cannot reproduce it. Open DevTools → Application → Manifest to see the fields the browser parsed, and Application → Service workers to watch the lifecycle from step 5.

08. Step 7: parse a 100,000-row import in a worker

JavaScript · public/import-worker.js
// import-worker.js — parse, validate, and write to IndexedDB in worker
self.onmessage = async (event) => {
  try {
    const rows = JSON.parse(event.data);
    const notes = rows
      .filter((row) => typeof row.text === 'string' && row.text.trim() !== '')
      .map((row, i) => ({
        id: row.id ?? i + 1,
        text: row.text,
        done: Boolean(row.done),
      }));
    const db = await new Promise((resolve, reject) => {
      const open = indexedDB.open('notes-app', 1);
      open.onsuccess = () => resolve(open.result);
      open.onerror = () => reject(open.error);
    });
    await new Promise((resolve, reject) => {
      const tx = db.transaction('notes', 'readwrite');
      const store = tx.objectStore('notes');
      for (const note of notes) store.put(note);
      tx.oncomplete = () => resolve();
      tx.onerror = () => reject(tx.error);
    });
    postMessage({ ok: true, count: notes.length });
  } catch (err) {
    postMessage({ ok: false, error: String(err) });
  }
};

The manifest from step 6 and this worker now exist, so they can join the offline shell. Change two lines at the top of public/sw.js: add both files to SHELL and bump VERSION, so the browser installs a new service worker that precaches them. Add them only now: cache.addAll rejects if any file in the list returns 404, and the whole install then fails without an error on the page.

JavaScript · public/sw.js (the first lines, changed in step 7)
const VERSION = 'notes-v3'; // bumped: the shell gained two files
const SHELL = ['/', '/app.js', '/db.js', '/styles.css',
  '/manifest.webmanifest', '/import-worker.js'];
JavaScript · public/app.js (part 4 of 4)
// 5. bulk import: worker parses, validates, and stores in IndexedDB
// NOTE: update public/sw.js as shown above and click Reload to update,
// so the cache-first service worker serves this updated app.js.
importButton.addEventListener('click', async () => {
  say('Importing archive…');
  const started = performance.now();
  try {
    const res = await fetch('/api/import');
    const worker = new Worker('/import-worker.js');
    worker.postMessage(await res.text());
    const report = await new Promise((resolve) => {
      worker.onmessage = (e) => resolve(e.data);
    });
    worker.terminate();
    if (!report.ok) throw new Error(report.error);
    render(await listNotes(db)); // the first 100 only
    const stored = await countNotes(db);
    const ms = Math.round(performance.now() - started);
    say(`Imported ${report.count} notes in ${ms} ms ` +
      `(${stored} stored in total)`);
  } catch (err) {
    say(`Import failed: ${err.message}`);
  }
});
Expected output (status line after clicking Import archive)
Imported 100000 notes in 4797 ms (100005 stored in total)

The raw text crosses into the worker (strings copy cheaply for their size), the parse, validation, and IndexedDB insertion all run off the main thread inside the worker, and only the small summary report ({ ok: true, count }) crosses back. Posting 100,000 objects instead would clone megabytes across threads. Back on the main thread, the page reads only what it draws: listNotes asks IndexedDB for the first 100 records (getAll(null, 100)) and countNotes for the total. An unbounded getAll() would deserialise all 100,000 records on the main thread just to keep 100 of them, a long task of its own, and it would repeat on every page load. In the Performance panel you can confirm that the parse and the inserts add no long task to the main thread. Your timing will differ; the shape of the line should not.

09. Troubleshooting

10. Check your understanding

Practice check · 3 questions

How the pieces hold together

Reason from the app you just built.

Q1. Why does app.js render from IndexedDB before fetching /api/notes?
Q2. In app.js part 3, the `controllerchange` handler reloads the page only when `updateAccepted` is true. What would happen without that check?
Q3. import-worker.js opens 'notes-app' at version 1 with no onupgradeneeded handler, yet its put() calls find the notes store. Why?
Practice only: not graded, not saved, not evidence.

11. Apply it: stretch tasks

These extend the app towards what the practice task asks for:

  1. Replay with re-authorisation. On reconnect, find notes with queued: true, send them again, and clear the flag on success. Before sending, confirm the session is still the same user — a queued write must never be sent under a different account's session.
  2. Sign-out cleanup. Wire a sign-out button that calls clearNotes(db), clears Web Storage keys the app owns, and re-syncs. Reload and confirm the next account sees none of the previous notes.
  3. Resync after reconnect. syncFromServer() already runs when a page that loaded offline reconnects. Extend it to pages that had synced before the network dropped: after the feed reopens, fetch /api/notes once and reconcile, so updates missed while offline appear.
  4. Measure the import. Record a Performance trace of a click on Import archive, and note where the time goes: worker parse, message copy, or IndexedDB transaction. Then try posting the records instead of the raw text, and compare.

12. Review prompt

Without looking back: which store holds what in this app, and why that split? Walk one offline session end to end — what is served from which store when the network is gone, and what happens to a note written then? What are the four steps between "bump VERSION in sw.js" and "the new version is running", and which of them involve the user? Finally: what crosses the thread boundary during the import, in each direction, and why is that split the cheap one?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check