Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 37 ยท Projects and Practice

Project: An Offline-First Notes App

Build an offline-first notes PWA: file layout, manifest, app shell cache, IndexedDB storage, an outbox with sync, an update toast, and a runnable simulation of the data flow.

This project pulls the course together. You will design a notes app that opens instantly, works with no connection, saves every edit on the device, and sends changes to the server when it can. The app is small on purpose, so every part can be explained: the manifest, the service worker, the local database, the outbox and the update flow.

The pieces run in a browser with a real service worker, which the interactive previews here cannot do. So the project is delivered in two forms: complete read-only files that you copy into a folder and serve over localhost, and runnable simulations that let you test the logic of each layer right here.

What we are building

Features

  • Create, edit and delete notes, even offline.
  • Notes load from the device database, so the list appears at once.
  • Changes queue in an outbox and sync when online; the UI shows what is pending.
  • Installable, with an update toast when a new version is ready.
flowchart TD
  UI["UI (index.html + app.js)"] --> DB["IndexedDB: notes + outbox"]
  UI -->|"register"| SW["Service worker"]
  SW -->|"precache shell"| C["Cache Storage"]
  SW -->|"sync event"| DB
  DB -->|"POST /api/notes"| API["Server API"]

File layout

TEXT
notes-app/
  index.html
  app.js          page logic and UI
  db.js           IndexedDB wrapper (shared with the worker)
  sw.js           service worker
  manifest.webmanifest
  offline.html
  icons/icon-192.png, icon-512.png, maskable-512.png

Step 1: manifest and page

JSON
{
  "id": "/",
  "name": "Offline Notes",
  "short_name": "Notes",
  "start_url": "/?source=pwa",
  "scope": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#1d4ed8",
  "icons": [
    { "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" },
    { "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png" },
    { "src": "/icons/maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
  ]
}
HTML
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="manifest" href="/manifest.webmanifest">
  <meta name="theme-color" content="#1d4ed8">
  <title>Offline Notes</title>
</head>
<body>
  <h1>Notes <small id="status"></small></h1>
  <form id="form"><input id="text" required><button>Add</button></form>
  <ul id="list"></ul>
  <script type="module" src="/app.js"></script>
</body>
</html>

Step 2: the data layer (db.js)

Both the page and the worker import this module, so there is a single definition of the schema. See offline data with IndexedDB for the details of each call.

JavaScript
const open = () => new Promise((resolve, reject) => {
  const request = indexedDB.open("notes-app", 1);
  request.onupgradeneeded = () => {
    const db = request.result;
    db.createObjectStore("notes", { keyPath: "id" });
    db.createObjectStore("outbox", { keyPath: "seq", autoIncrement: true });
  };
  request.onsuccess = () => resolve(request.result);
  request.onerror = () => reject(request.error);
});

export async function saveNote(note, operation) {
  const db = await open();
  return new Promise((resolve, reject) => {
    const tx = db.transaction(["notes", "outbox"], "readwrite");
    if (operation.type === "delete") tx.objectStore("notes").delete(note.id);
    else tx.objectStore("notes").put(note);
    tx.objectStore("outbox").add(operation);      // same transaction: both or neither
    tx.oncomplete = resolve;
    tx.onerror = () => reject(tx.error);
  });
}
// listNotes(), readOutbox(), removeFromOutbox(seq) follow the same pattern

Step 3: the service worker (sw.js)

JavaScript
import { readOutbox, removeFromOutbox } from "/db.js";

const SHELL = "shell-v1";
const SHELL_FILES = ["/", "/app.js", "/db.js", "/offline.html", "/icons/icon-192.png"];

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

self.addEventListener("activate", (event) => {
  event.waitUntil(
    caches.keys().then((names) =>
      Promise.all(names.filter((n) => n !== SHELL).map((n) => caches.delete(n)))
    ).then(() => self.clients.claim())
  );
});

self.addEventListener("fetch", (event) => {
  const { request } = event;
  if (request.method !== "GET" || new URL(request.url).origin !== location.origin) return;
  if (request.url.includes("/api/")) return;                        // data goes through the outbox

  event.respondWith(
    caches.match(request).then((cached) =>
      cached ?? fetch(request).catch(() =>
        request.mode === "navigate" ? caches.match("/offline.html") : Response.error()
      )
    )
  );
});

self.addEventListener("sync", (event) => {
  if (event.tag === "notes-outbox") event.waitUntil(flush());
});

self.addEventListener("message", (event) => {
  if (event.data?.type === "SKIP_WAITING") self.skipWaiting();
});

async function flush() {
  for (const op of await readOutbox()) {
    const response = await fetch("/api/notes", {
      method: "POST",
      headers: { "Content-Type": "application/json", "Idempotency-Key": op.id },
      body: JSON.stringify(op),
    });
    if (!response.ok) throw new Error("sync failed: " + response.status);
    await removeFromOutbox(op.seq);
  }
}

The import at the top works because the worker is registered with { type: "module" }. If you target an older browser, bundle it or use importScripts.

Step 4: the page logic (app.js)

JavaScript
import { saveNote, listNotes } from "/db.js";

const registration = await navigator.serviceWorker.register("/sw.js", { type: "module" });
// ...update toast code from "Updating a PWA"...

document.querySelector("#form").addEventListener("submit", async (event) => {
  event.preventDefault();
  const input = document.querySelector("#text");
  const note = { id: crypto.randomUUID(), text: input.value, updatedAt: Date.now() };
  await saveNote(note, { id: crypto.randomUUID(), type: "create", noteId: note.id, payload: note });
  input.value = "";
  await render();
  const ready = await navigator.serviceWorker.ready;
  if ("sync" in ready) ready.sync.register("notes-outbox"); else flushFromPage();
});

addEventListener("online", flushFromPage);
render();

The fallbacks matter: Safari and Firefox do not support Background Sync, so the page flushes on online and on load. The update flow is the one from updating a PWA.

Try it: the data flow in one simulation

This runnable model contains the same logic as saveNote, the outbox and flush with a flaky fake server:

JS Notes, outbox and sync (simulation)

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

No output.

Try it: a visual version

This miniature shows the user-facing behavior: add notes while "offline", watch the pending counter, then go online. It keeps data in memory only because preview pages have no storage.

Notes with an offline switch

Test checklist

  1. Serve over http://localhost. DevTools, Application: confirm the manifest has no errors and the worker is activated.
  2. Tick Offline in the Network tab; reload. The shell and notes must appear.
  3. Add notes offline, check the outbox in IndexedDB, then go online and confirm they sync once only.
  4. Change SHELL to shell-v2, redeploy, and confirm the update toast and the old cache's removal.
  5. Run Lighthouse; fix anything it reports under Performance and Best Practices.

Extensions

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why are the note and the outbox operation saved in one transaction?

    A single transaction keeps local data and the pending queue consistent.
  2. 2. Why does the fetch handler skip /api/ requests?

    Blindly cache-first API calls would return stale data; this app keeps its own data layer.
  3. 3. What replaces Background Sync in Safari and Firefox here?

    The page flushes itself when it runs, which covers browsers without the Sync API.
  4. 4. Why is a unique idempotency key sent with each operation?

    The server remembers keys and returns the earlier result for repeats.

Summary

  • The app shell is precached, notes live in IndexedDB, and edits flow through an outbox.
  • The same data module serves the page and the worker.
  • Sync uses Background Sync where available and a page-driven fallback everywhere else.
  • Version the shell cache and show an update toast.
  • Test offline, the upgrade path and Lighthouse before shipping.

Next: Project: A News Reader with Caching Strategies