/web-app-patterns:offline-first-pwafrom web-app-patterns
Build (or retrofit) a personal web app as an installable PWA that works fully offline — Dexie local DB, a pendingSync mutation queue, a bidirectional sync engine, service-worker update prompt, and the mobile/native-feel baseline. Use when the user asks for offline support, "make this a PWA", local-first/offline-first data, a sync engine, Dexie/IndexedDB caching, or a new personal app that must work with no network. Also use when auditing an existing app against this architecture.
Ships in web-app-patterns. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
An opinionated, batteries-included recipe for one specific shape of app: a small-to-medium personal or team app, one writer per record, that must keep working with no network and reconcile when it comes back. It is not a general survey — where there is a choice, this picks one option and says why.
If you apply it to more than one app, keep the implementations aligned — a divergent sync protocol is a bug, not a variation. The details below are deliberately prescriptive for that reason.
If you need multi-writer concurrent editing with automatic conflict merging, stop here and use a CRDT library (Yjs, Automerge) instead. This design resolves conflicts server-wins, which is correct for personal apps and wrong for collaborative documents.
The invariant that defines it: the client never reads from the network directly.
write: component → Dexie (instant) → pendingSync queue → server when online
read: component ← Dexie (instant) ← background refresh from server
Everything below exists to make those two lines true without losing data.
Answer these four. They change the code, not just the config.
| Question | Why it matters |
|---|---|
| Stack? Vite+React / SvelteKit / Next.js App Router | Decides vite-plugin-pwa vs @vite-pwa/sveltekit vs @serwist/next (§2) |
| Backend? Express+SQLite / FastAPI+Postgres / Next.js route handlers | Decides the /sync endpoint dialect (§5) |
| Server ID type? integer autoincrement / cuid / uuid | serverId: number vs serverId: string. Pick one and never mix. |
| Multi-account browser? Can two people sign in on one device? | If yes, every row and queue entry MUST be tagged userId (§7.1). Retrofitting this later costs a Dexie migration and a cross-user data leak. |
Do not start until every one is answered. Guessing on the last one is expensive: an app that assumed one account per device needed a schema migration, a rewrite of every read, and a cross-user data leak fixed in production before it was right.
npm i dexie
# then ONE of:
npm i -D vite-plugin-pwa # Vite + React/Vue/vanilla
npm i -D @vite-pwa/sveltekit vite-plugin-pwa # SvelteKit
npm i @serwist/next serwist @serwist/window # Next.js App Router
Known-good versions at the time of writing: dexie ^4.3.0,
vite-plugin-pwa ^1.2.0, @vite-pwa/sveltekit ^1.1.0, serwist ^9.5.7.
Build the stages in this order. Each is independently shippable; skipping ahead produces an app that looks offline-capable and silently loses writes.
src/lib/db.ts Dexie schema — the ONLY place versions are declared
src/lib/sync.ts queue, flush, pull, merge
src/lib/merge-lock.ts serializes every server→Dexie merge (§7.2)
src/lib/offline-api.ts the read/write layer components actually call
src/components/SyncStatus dot + pending badge + queue inspector
src/components/SWUpdatePrompt
public/manifest.json (or generated by the PWA plugin)
public/icons/icon-{192,512}.png
server: /api/sync/changes (GET), /api/sync/push (POST)
promptNever autoUpdate. The update prompt is what guarantees users get new JS
before Dexie opens, so schema migrations run on the first load after an
update. An auto-updating SW can activate mid-session with the old JS still
holding an open Dexie connection at the previous version. Do not drop the
prompt.
vite.config.ts:
import { VitePWA } from 'vite-plugin-pwa';
VitePWA({
registerType: 'prompt',
includeAssets: ['favicon.png', 'apple-touch-icon-180x180.png'],
manifest: {
name: 'App Name',
short_name: 'App',
description: '…',
theme_color: '#7c3aed',
background_color: '#f8fafc',
display: 'standalone',
scope: '/',
start_url: '/',
icons: [
{ src: '/icon-192.png', sizes: '192x192', type: 'image/png', purpose: 'any maskable' },
{ src: '/icon-512.png', sizes: '512x512', type: 'image/png', purpose: 'any maskable' },
],
},
workbox: {
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2}'],
navigateFallback: 'index.html',
// /api/ must be denied or the SW answers API navigations from the shell.
// Add /auth/ too if auth routes are server-rendered — otherwise a cached
// shell answers /auth/logout and the session cookie is never cleared.
navigateFallbackDenylist: [/^\/api\//, /^\/auth\//],
runtimeCaching: [
// The sync endpoints are NEVER cached. The sync engine owns freshness.
{ urlPattern: /\/api\/sync\/.*/i, handler: 'NetworkOnly' },
// Large immutable blobs (images, attachments) — CacheFirst with expiry.
{
urlPattern: /\/api\/attachments\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'attachments',
expiration: { maxEntries: 200, maxAgeSeconds: 60 * 60 * 24 * 90 },
cacheableResponse: { statuses: [0, 200] },
},
},
],
},
})
Ship exactly two icons, 192 and 512, both fully opaque, full-bleed, both
declared purpose: 'any maskable'.
Do not add a separate purpose: 'any' icon with transparent corners. Android
composites the transparency onto a white plate and then insets the result —
that is the white padding and the shrunk-to-two-thirds icon. A full-bleed icon
declared any maskable lets Android apply its own mask, so it comes out round
on a circular launcher with no transparent pixel involved. The round look comes
from the mask, never from the file.
@vite-pwa/sveltekit generates and serves /manifest.webmanifest but does
not inject the <link> into src/app.html, which SvelteKit renders
verbatim. Without the link nothing ever reads the manifest, Chrome falls back to
the favicon, and no amount of icon editing fixes it. Add by hand:
<link rel="manifest" href="/manifest.webmanifest" />
Also in app.html / index.html:
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#7c3aed" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="apple-mobile-web-app-title" content="App" />
<link rel="apple-touch-icon" href="/apple-touch-icon-180x180.png" />
viewport-fit=cover is required or env(safe-area-inset-*) resolves to 0 on
iOS standalone and the bottom nav sits under the home indicator.
Never set user-scalable=no / maximum-scale=1 — it breaks pinch-zoom on
Android and violates WCAG 1.4.4.
next.config.mjs:
import withSerwistInit from "@serwist/next";
const withSerwist = withSerwistInit({
swSrc: "src/app/sw.ts",
swDest: "public/sw.js",
register: false, // manual registration, so we control the update prompt
});
export default withSerwist({ reactStrictMode: true, output: "standalone" });
src/app/sw.ts:
/// <reference lib="webworker" />
import { defaultCache } from "@serwist/next/worker";
import { Serwist, CacheFirst, NetworkOnly, ExpirationPlugin, type SerwistGlobalConfig } from "serwist";
declare global { interface WorkerGlobalScope extends SerwistGlobalConfig {} }
declare const self: ServiceWorkerGlobalScope;
new Serwist({
// @ts-expect-error injected by @serwist/next at build time
precacheEntries: self.__SW_MANIFEST,
skipWaiting: false, // prompt-based updates — the user decides
clientsClaim: true,
navigationPreload: true,
runtimeCaching: [
{ matcher: /\/api\//, handler: new NetworkOnly() },
...defaultCache,
],
}).addEventListeners();
layout.tsx viewport:
export const viewport: Viewport = {
width: "device-width",
initialScale: 1,
viewportFit: "cover", // required for env(safe-area-inset-*)
themeColor: "#7c3aed",
};
export const metadata: Metadata = {
manifest: "/manifest.json",
appleWebApp: { capable: true, statusBarStyle: "black-translucent", title: "App" },
};
Vite (React):
import { useRegisterSW } from 'virtual:pwa-register/react';
export default function SWUpdatePrompt() {
const { needRefresh: [needRefresh, setNeedRefresh], updateServiceWorker } = useRegisterSW({
onRegisteredSW(_url, registration) {
// Poll for a new build hourly — a PWA left open for days otherwise
// never learns an update exists.
if (registration) setInterval(() => registration.update(), 60 * 60 * 1000);
},
});
if (!needRefresh) return null;
return (
<div className="banner">
<span>New version available</span>
<button onClick={() => updateServiceWorker(true)}>Update</button>
<button onClick={() => setNeedRefresh(false)} title="Dismiss">×</button>
</div>
);
}
Dismiss must leave the SW waiting, not skip it — the user updates later, and the next load still gets the new JS before Dexie opens.
Next.js (Serwist) — two things are easy to get wrong:
const serwist = new Serwist("/sw.js", { scope: "/" });
// 1. Attach the listener BEFORE register(), or the "waiting" event fires
// for an already-installed pending SW and is missed on page load.
serwist.addEventListener("waiting", () => setNeedsUpdate(true));
await serwist.register();
// 2. A worker already waiting at registration time never fires "waiting".
if (navigator.serviceWorker?.controller) {
const reg = await navigator.serviceWorker.getRegistration();
if (reg?.waiting) setNeedsUpdate(true);
}
and apply:
sw.messageSkipWaiting();
navigator.serviceWorker.addEventListener("controllerchange", () => window.location.reload(), { once: true });
In dev, unregister the SW. A stale production public/sw.js fights HMR and
404s on its precached asset list:
if (process.env.NODE_ENV !== "production") {
navigator.serviceWorker.getRegistrations()
.then(rs => Promise.all(rs.map(r => r.unregister()))).catch(() => {});
return;
}
src/lib/db.ts)/**
* Dexie.js client-side database for offline-first data access.
*
* SCHEMA VERSIONING RULES (for future agents):
* ─────────────────────────────────────────────
* 1. Versions are APPEND-ONLY — never delete or modify old db.version() blocks.
* 2. Each schema change requires a new db.version(N+1) block with an .upgrade().
* 3. Dexie runs all necessary migrations sequentially when the database opens
* (a user on v1 opening v3 runs v1→v2→v3 automatically).
* 4. The SW update prompt ensures users get new JS before Dexie opens,
* so migrations run on the first page load after an app update.
* 5. Only INDEXED columns are listed in .stores() — all other fields are still
* stored. Adding a non-indexed field needs NO version bump.
* 6. Test migration paths: v1→v2, v1→v3 (skip), v2→v3.
*
* INDEX SYNTAX:
* ++localId auto-increment primary key
* serverId indexed field
* [a+b] compound index
* &field unique index
*/
export interface LocalItem {
localId?: number; // client identity, auto-increment PK
serverId?: number; // null until first sync — NEVER reuse localId here
userId?: number; // owner; required if a browser can hold 2 accounts
updatedAt: string; // ISO, set on every local write
_deleted?: boolean; // soft delete — hidden from reads, row kept until
// the server confirms the delete
// …domain fields
}
export type SyncOperation = 'create' | 'update' | 'delete';
export interface PendingSyncEntry {
id?: number;
table: string; // Dexie table name; must match the
// server's TABLE_MAP key exactly
operation: SyncOperation;
localId: number;
serverId?: number;
data?: Record<string, unknown>; // the mutation payload
timestamp: string; // ISO, push order
retries: number;
userId?: number; // who queued it — see §7.1
}
import Dexie, { type Table } from 'dexie';
class AppDatabase extends Dexie {
items!: Table<LocalItem, number>;
settings!: Table<{ key: string; value: unknown }, string>;
pendingSync!: Table<PendingSyncEntry, number>;
constructor() {
super('appname');
// ── Version 1: initial schema ──
this.version(1).stores({
items: '++localId, serverId, userId, updatedAt',
settings: 'key',
pendingSync: '++id, table, operation, localId, serverId, timestamp, userId',
});
// ── Version 2: <what changed and why> ──
// Carry EVERY table forward, even unchanged ones, or Dexie drops them.
// this.version(2).stores({ … }).upgrade(async (tx) => {
// await tx.table('items').toCollection().modify(r => { r.newField = 'default'; });
// });
}
}
export const db = new AppDatabase();
Two things that bite:
.stores() block must list every table, not just the changed one..upgrade()./**
* Everything in this DB is per-account. `keepPendingSync` preserves the
* offline mutation queue — the only copy of work that never reached the
* server. Kept entries stay tagged with the account that made them and are
* pushed only when that account signs back in, so keeping them cannot leak.
*/
export async function clearLocalUserData(keepPendingSync = true): Promise<void> {
const preserved = keepPendingSync ? await db.pendingSync.toArray() : [];
await Promise.all(db.tables.map(t => t.clear()));
if (preserved.length) await db.pendingSync.bulkAdd(preserved);
// Runtime caches holding user bytes (images, attachments) must go too, or
// they are served to whoever signs in next.
try { await caches.delete('attachments'); } catch { /* best effort */ }
}
Components call offlineApi.*, never fetch and never Dexie directly. Keep
the method signatures identical to the old network API client so components
migrate one import at a time.
export const dataVersion = writable(0); // or useSyncExternalStore in React
const inFlight = new Set<string>();
const lastRevalidated = new Map<string, number>();
const REVALIDATE_MIN_INTERVAL_MS = 2000;
const BUMP_COALESCE_MS = 50;
/** Fire-and-forget refresh, deduped by key. Failures are silent — offline is
* the normal case — and NEVER clear cached data. */
function revalidate(key: string, task: () => Promise<boolean>): void {
if (inFlight.has(key)) return;
if (Date.now() - (lastRevalidated.get(key) ?? 0) < REVALIDATE_MIN_INTERVAL_MS) return;
inFlight.add(key);
lastRevalidated.set(key, Date.now());
task()
.then(changed => { if (changed) bumpDataVersion(); })
.catch(() => {})
.finally(() => inFlight.delete(key));
}
async getItems(): Promise<Item[]> {
const uid = currentUserId();
if (uid == null) return api.getItems(); // signed out: nothing cached is attributable
revalidate(`items:${uid}`, async () => {
const rows = await api.getItems(); // fetch OUTSIDE the merge lock
return mergeForUser(uid, () => mergeServerRows('items', db.items, rows, uid));
});
return (await db.items.toArray())
.filter(r => r.userId === uid && !r._deleted)
.map(fromLocal);
}
dataVersion must bump only when the merge actually changed something, or
$: $dataVersion → reload() loops forever. Compare field-by-field, ignoring
updatedAt (it is regenerated on every fetch by design).
Coalesce bumps on a 50 ms timer — cold start hydrates several tables at once and should cause one re-read, not N.
async createItem(data: ItemInput): Promise<Item> {
const local: LocalItem = { ...data, userId: currentUserId(), updatedAt: now() };
const localId = await db.items.add(local); // UI is already correct
try {
const server = await api.createItem(data);
await db.items.update(localId, { serverId: server.id });
return server;
} catch {
await queueSync('items', 'create', localId, undefined, data);
return fromLocal({ ...local, localId });
}
}
async deleteItem(id: number): Promise<void> {
const existing = await findOwnedRow(db.items, id, currentUserId());
if (!existing) return;
// Soft delete locally: hidden from reads, but the row survives until the
// server confirms. A hard delete here destroys the only copy of a row the
// server has never seen.
await db.items.update(existing.localId!, { _deleted: true, updatedAt: now() });
try {
await api.deleteItem(existing.serverId ?? id);
await db.items.delete(existing.localId!);
} catch {
await queueSync('items', 'delete', existing.localId!, existing.serverId);
}
}
id reaching an update/delete may be a serverId or a localId (a row
created offline has no serverId yet). Resolve both, scoped to the owner:
async function findOwnedRow<T extends LocalItem>(table: Table<T, number>, id: number, uid?: number) {
const byServer = (await table.where('serverId').equals(id).toArray()).filter(r => r.userId === uid);
if (byServer.length) return pickCanonicalRow(byServer);
const byLocal = await table.get(id);
return byLocal && byLocal.userId === uid ? byLocal : undefined;
}
Two endpoints. Both require auth. Both scope every row to the session user — never to a user id in the payload.
GET /api/sync/changes?since=<ISO>Return every row where updated_at > since OR deleted_at > since, per
table, scoped to the caller. Soft-deleted rows must be included — the tombstone
is how the client learns to drop its copy.
// Express + better-sqlite3
router.get('/changes', (req, res) => {
const since = (req.query.since as string) || '1970-01-01T00:00:00.000Z';
const userId = req.user!.id;
const items = db.prepare(`
SELECT * FROM items
WHERE user_id = ? AND (updated_at > ? OR deleted_at > ?)
ORDER BY updated_at ASC
`).all(userId, since, since);
res.json({ items, serverTime: new Date().toISOString() });
});
# FastAPI + SQLAlchemy
@router.get("/changes")
def get_changes(since: str = Query(...), db=Depends(get_db), user=Depends(get_current_user)):
since_dt = parse_iso(since)
result = {}
for name, model in TABLE_MAP.items():
filters = [model.updated_at > since_dt]
if hasattr(model, "deleted_at"): # not every model soft-deletes
filters.append(model.deleted_at > since_dt)
q = db.query(model).filter(or_(*filters))
if hasattr(model, "user_id"):
q = q.filter(model.user_id == user.id)
rows = q.all()
if rows:
result[name] = [model_to_dict(r) for r in rows]
return result
TABLE_MAP keys must match the client's Dexie table names exactly — a
pendingSync entry's table field is resolved through it in both directions.
POST /api/sync/pushBody: { changes: PendingSyncEntry[] } in timestamp order.
Response: { results: [{ id, success, serverId?, error? }], idMappings: [{ table, localId, serverId }] }
Non-negotiables:
rollback() after a failed change — otherwise the session is
in needs-rollback state, every subsequent change dies with
PendingRollbackError, the request 500s, and the client retries the same
poison batch forever. One bad row must never wedge the queue.created_ids: (table, localId) → serverId
as you go. A row created offline then edited/deleted offline queues a
follow-up carrying no serverId; resolve it from the create earlier in the
same batch. Without this, an offline create+delete leaves the row alive on
the server and create+update inserts a second copy.existing.user_id !== userId
→ error, not a write.updated_at:
if (payload.updated_at && existing.updated_at > payload.updated_at) return;
— skip the write, still report success, the next pull corrects the client.SET deleted_at = now(), updated_at = now(), and
cascade the tombstone to children (comments, todos, …) or the client
never learns they went.for (const change of changes) {
const { table, operation, localId, serverId, payload, id: changeId } = change;
try {
const r = processChange(table, operation, serverId, payload, userId, localId);
results.push({ id: changeId, success: true, serverId: r.serverId });
if (r.isNew && localId) idMappings.push({ table, localId, serverId: r.serverId });
} catch (err: any) {
results.push({ id: changeId, success: false, error: err.message });
}
}
res.json({ results, idMappings });
src/lib/sync.ts)let _online = navigator.onLine;
const _listeners = new Set<(o: boolean) => void>();
// Attach the window listeners exactly ONCE for the page's lifetime. A pair
// per subscriber leaks under React StrictMode and re-renders.
window.addEventListener('online', () => { _online = true; _listeners.forEach(f => f(true)); flushPendingSync(); });
window.addEventListener('offline', () => { _online = false; _listeners.forEach(f => f(false)); });
export const isOnline = () => _online;
export function onConnectivityChange(fn: (o: boolean) => void) {
_listeners.add(fn);
return () => _listeners.delete(fn);
}
export async function queueSync(table, operation, localId, serverId?, data?) {
await db.pendingSync.add({
table, operation, localId, serverId, data,
timestamp: new Date().toISOString(),
retries: 0,
userId: currentUserId(),
});
if (_online) flushPendingSync(); else registerBackgroundSync();
}
/**
* A row created offline and deleted again while still offline queues
* create(localId=L, serverId=undefined) then delete(localId=L, serverId=undefined).
* Pushed as-is, the create inserts a server row and the delete has nothing to
* aim at, so the row survives and the next pull drags the user's deleted entry
* back into the local DB.
*
* Only fully-unsynced groups qualify. One entry carrying a serverId means the
* row exists on the server, so the delete has real work — push the group intact.
* Entries must be in push (timestamp) order.
*/
export function collapseQueue(entries: PendingSyncEntry[]) {
const groups = new Map<string, PendingSyncEntry[]>();
for (const e of entries) {
const key = `${e.table}:${e.localId}`;
const g = groups.get(key);
if (g) g.push(e); else groups.set(key, [e]);
}
const dead = new Set<string>();
for (const [key, g] of groups) {
if (g[g.length - 1].operation !== 'delete') continue;
if (g.some(e => e.serverId != null)) continue;
if (!g.some(e => e.operation === 'create')) continue;
dead.add(key);
}
const toPush: PendingSyncEntry[] = [];
const dropIds: number[] = [];
for (const e of entries) {
if (dead.has(`${e.table}:${e.localId}`)) { if (e.id != null) dropIds.push(e.id); }
else toPush.push(e);
}
return { toPush, dropIds };
}
const MAX_RETRIES = 10;
export async function flushPendingSync(): Promise<void> {
if (!_online || isSyncing) return;
isSyncing = true;
try {
const uid = currentUserId();
const queued = (await db.pendingSync.orderBy('timestamp').toArray())
.filter(e => isQueueEntryOwnedBy(e, uid) && e.retries < MAX_RETRIES);
if (!queued.length) return;
// Ties on timestamp (two writes in the same millisecond) fall back to
// insertion order — the order the user actually made them in.
queued.sort((a, b) => a.timestamp.localeCompare(b.timestamp) || (a.id ?? 0) - (b.id ?? 0));
const { toPush, dropIds } = collapseQueue(queued);
if (dropIds.length) await db.pendingSync.bulkDelete(dropIds);
if (!toPush.length) return;
const res = await fetch('/api/sync/push', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ changes: toPush }),
});
if (res.status === 404) { // endpoint not deployed yet
setSyncError({ type: 'server', message: 'Sync endpoint not available — changes saved locally' });
return; // keep every entry queued
}
if (!res.ok) {
setSyncError({ type: 'server', message: `Sync failed (${res.status}) — will retry` });
await incrementRetries(toPush);
return;
}
const { results, idMappings } = await res.json();
// Adopt server ids BEFORE dropping queue entries. If this throws, the
// entries are still queued and the push retries — the alternative is a row
// stranded with serverId == null and nothing left to tell it its id.
if (idMappings) await applyServerIdMappings(idMappings);
const ok = new Set(results.filter((r: any) => r.success).map((r: any) => r.id));
const doneIds = toPush.filter(p => ok.has(p.id)).map(p => p.id!).filter(Boolean);
if (doneIds.length) await db.pendingSync.bulkDelete(doneIds);
const failed = toPush.filter(p => !ok.has(p.id));
if (failed.length) await incrementRetries(failed);
clearSyncError();
} catch {
setSyncError({ type: 'network', message: 'Network error — changes saved locally, will retry' });
} finally {
isSyncing = false;
}
}
The costliest bug this design has produced: clearing the whole
pendingSync table after a successful HTTP 200. A partial success then silently
destroys the entries the server rejected, and the user's work is gone with no
error anywhere. Delete only the ids the server confirmed. Never
db.pendingSync.clear().
/**
* Without this a row created offline never learns its server id: the next pull
* can't match it, inserts a second copy alongside it, and every later edit of
* that ghost sends its LOCAL id to the server as if it were a server id —
* overwriting an unrelated record.
*
* - Write only the serverId field, so an edit made while the push was in
* flight is untouched.
* - Do not re-add a row deleted meanwhile; that would undo the delete. Still
* backfill its queue entries so the queued delete can find the server row.
* - Leave a row that already has a serverId alone — something already
* reconciled it and that id is the one the rest of the DB refers to.
*/
async function applyServerIdMappings(maps: Array<{table: string; localId: number; serverId: number}>) {
for (const { table, localId, serverId } of maps) {
const t = SYNCED_TABLES[table];
if (!t) continue;
const row = await t.get(localId);
if (row && row.serverId == null) await t.update(localId, { serverId });
await db.pendingSync.where({ table, localId }).modify(e => { if (e.serverId == null) e.serverId = serverId; });
}
}
export async function pullFromServer(): Promise<void> {
if (!_online) return;
const ownerId = currentUserId();
if (ownerId == null) return; // nothing to file rows under
const lastSync = await loadLastSyncTime(); // persisted in Dexie settings
const res = await fetch(`/api/sync/changes?since=${encodeURIComponent(lastSync)}`, { credentials: 'include' });
if (res.status === 404 || !res.ok) return;
const data = await res.json();
// The whole merge is ONE critical section — see §7.2.
await serializeMerge(() => mergeServerChanges(data, ownerId));
await saveLastSyncTime(new Date().toISOString());
}
export async function sync(): Promise<void> {
await pullFromServer(); // pull first: get latest state
await flushPendingSync(); // then push local work on top
}
Persist the cursor in Dexie settings, not localStorage, once you have more
than one tab or a service worker involved. localStorage is synchronous,
unpartitioned across tabs and invisible to the SW, so two tabs racing the same
pull can each advance the cursor past changes the other consumed.
async function mergeServerRecord(tableName, serverRecord, ownerId, dateIsUnique, pendingLocalIds) {
const table = SYNCED_TABLES[tableName];
if (!table) return;
// Not .first(): two local rows can claim one serverId (stranded by an older
// merge), and the survivor must be the one the read layer serves.
const matches = await table.where('serverId').equals(serverRecord.id).toArray();
let existing = pickCanonicalRow(matches);
const matchedByServerId = existing !== undefined;
if (matches.length > 1) {
const strays = matches
.filter(r => r !== existing && r.localId != null && !pendingLocalIds.has(r.localId))
.map(r => r.localId as number);
if (strays.length) await table.bulkDelete(strays); // never drop unsent work
}
// Natural-key fallback exists ONLY to adopt a local create the server hasn't
// assigned an id to yet. Restricting it to serverId == null keeps it from
// overwriting an already-synced row that merely shares a key; restricting it
// to the owner keeps one account's pull from swallowing the other's row.
if (!existing && dateIsUnique && serverRecord.date) {
existing = pickCanonicalRow(await table.where('date').equals(serverRecord.date)
.filter(r => r.serverId == null && r.userId === ownerId).toArray());
}
if (serverRecord.deleted_at) {
// Delete only what matched by serverId. A natural-key match is a guess,
// and this destroys a row whose only copy may be local.
if (existing && matchedByServerId) await table.delete(existing.localId);
return;
}
const merged = {
...serverRecord,
serverId: serverRecord.id,
userId: typeof serverRecord.user_id === 'number' ? serverRecord.user_id : ownerId,
updatedAt: serverRecord.updated_at || new Date().toISOString(),
};
if (existing) await table.update(existing.localId, merged);
else await table.add(merged);
}
dateIsUnique (or whatever your natural key is) is an application invariant,
not a schema one. Set it true only for tables the UI edits as "the row for this
day/key". For a table that legitimately holds many rows per date, matching on
date picks an arbitrary unrelated row.
A row with an unflushed mutation is never overwritten by a merge and never swept as a duplicate. The local DB is the only copy of that work.
/**
* When two local rows describe the same thing:
* 1. A row the server has seen (serverId != null) beats one it hasn't — it is
* the row every later merge matches, and the one whose edits can be pushed.
* 2. Otherwise the lowest localId wins: oldest row, most likely referenced by
* the rest of the DB, and stable across re-runs.
*
* EVERY caller uses this — list rendering, single-row lookups, saves, cleanup
* sweeps. When the list view and the detail view disagreed about which
* duplicate was real, the detail view wrote to a row the list never rendered
* and the edit looked like it did nothing.
*/
export function preferRow<T extends { localId?: number; serverId?: number }>(a: T, b: T): T {
const aS = a.serverId != null, bS = b.serverId != null;
if (aS !== bS) return aS ? a : b;
return (a.localId ?? Infinity) <= (b.localId ?? Infinity) ? a : b;
}
export function pickCanonicalRow<T extends { localId?: number; serverId?: number }>(rows: T[]): T | undefined {
let best: T | undefined;
for (const row of rows) best = best === undefined ? row : preferRow(best, row);
return best;
}
async function incrementRetries(records: PendingSyncEntry[]) {
let exhausted = 0;
for (const r of records) {
if (!r.id) continue;
const n = r.retries + 1;
await db.pendingSync.update(r.id, { retries: n });
if (n >= MAX_RETRIES) exhausted++;
}
if (exhausted) setSyncError({ type: 'failed-records', failedCount: exhausted,
message: `${exhausted} change(s) failed to sync after ${MAX_RETRIES} attempts` });
}
export const getFailedSyncCount = () => db.pendingSync.where('retries').aboveOrEqual(MAX_RETRIES).count();
export async function retryFailedSync() {
await db.pendingSync.where('retries').aboveOrEqual(MAX_RETRIES).modify({ retries: 0 });
clearSyncError();
flushPendingSync();
}
Exhausted entries are parked, never dropped. The UI must expose them and a manual retry, or the user's work vanishes with no trace.
function registerBackgroundSync() {
if ('serviceWorker' in navigator && 'SyncManager' in window) {
navigator.serviceWorker.ready.then(reg =>
(reg as any).sync?.register('app-sync').catch(() => {}));
}
}
Chrome/Android only. Never the primary path — the online event is.
At app mount, after the user is known:
hydrateFromServer(user.id).catch(() => {}); // fill empty tables on first run
sync().catch(() => {}); // pull, then push
Paint from the cached identity first; /auth/me must not gate first render.
If the session's user differs from the cached one, clearLocalSession(true)
before a single read can serve the previous account's rows.
Violating any of these is a bug. They are listed in the order they were learned the hard way.
db.version() block.
Add version(N+1) with an .upgrade().localId, serverId (null until first sync), updatedAt, and
_deleted. A hard local delete of an unsynced row destroys the only copy./api/sync/* is NetworkOnly in the service worker. The sync engine owns
freshness; a cached change feed replays stale tombstones.If two people can sign in on one device (household apps), then:
userId === currentUserId(); every cached write
stamps it. A row with no userId belongs to nobody and is served to nobody.flushPendingSync pushes only the current account's entries. A queue
parked by whoever signed out last stays put until they sign back in — pushing
it under the current session files their data into the wrong account.Two paths write server data into Dexie: cold-start hydration (bulk, per table)
and the incremental /changes feed. Both are read-then-write built from
separate awaits. Without a lock they interleave: one reads an empty table,
yields at an await, the other inserts the whole dataset, then the first
inserts anyway — the entire dataset, twice, on a fresh browser.
Ordering the two calls at startup does not fix it; both are reachable independently afterwards. The mutual exclusion lives at the merge.
// src/lib/merge-lock.ts — imports nothing, so sync.ts and the data layer can
// both use it without an import cycle.
let mergeChain: Promise<unknown> = Promise.resolve();
/** Run fn once every previously scheduled merge has settled. Only the
* read-modify-write is serialized — do the network fetch BEFORE entering, so
* concurrent revalidations still overlap on the wire. A rejection propagates
* to that caller only; the chain keeps running. */
export function serializeMerge<T>(fn: () => Promise<T>): Promise<T> {
const next = mergeChain.then(fn, fn);
mergeChain = next.catch(() => {});
return next;
}
Abandon a merge whose account changed mid-flight:
const mergeForUser = (uid, merge) =>
serializeMerge(() => currentUserId() === uid ? merge() : Promise.resolve(false));
Skip this until a table genuinely cannot fit on the device; a few thousand rows
of JSON does not need it, and the machinery is easy to get wrong. When you do
add it, hold rules 3–5 above literally: prune by age with a plain bulkDelete
that touches nothing else, skip any row whose localId appears in
pendingSync, and keep the retention horizon in a settings key separate from
the sync cursor. Re-fetch on demand when the user scrolls past the window.
Three pieces, all required.
SyncStatus — a dot plus a badge, and clicking it opens the queue.
| State | Dot | Label |
|---|---|---|
| offline | amber | "Offline" |
| failed entries or sync error | red | "N failed" |
| pending > 0 | blue/pulsing | pending count |
| clean | green | "Connected" |
Poll getPendingSyncCount() and getFailedSyncCount() on a 3 s interval, and
subscribe to onConnectivityChange / onSyncErrorChange. The detail panel
lists each queued entry — operation, table, a title from the payload, a
relative timestamp, and retry N/10 (or FAILED) — plus a Retry N failed
button. Without this panel a wedged queue is invisible and undiagnosable.
SWUpdatePrompt — §2.6.
SyncErrorToast — auto-dismissing, 5–10 s, plus a listener for the
sync-conflict event ("Server updated — your changes were overwritten") so
server-wins is never silent.
Put the status dot in the header on desktop and as a badge on the bottom nav on mobile.
html, body { overflow-x: hidden; max-width: 100vw; }
html { -webkit-tap-highlight-color: transparent; scrollbar-gutter: stable; }
/* 100dvh, not 100vh — vh includes the collapsing mobile URL bar. */
.app-shell { min-height: 100dvh; }
.safe-area-bottom { padding-bottom: env(safe-area-inset-bottom, 0px); }
.safe-area-top { padding-top: env(safe-area-inset-top, 0px); }
button, [role="button"], a { touch-action: manipulation; } /* kills the 300ms delay */
.draggable-card { touch-action: pan-y; } /* keep vertical scroll */
Plus: bottom nav on mobile, :focus-visible rings only (not :focus), and
user-scalable left alone.
Sync engines are poorly served by unit tests — nearly every real failure is an ordering or connectivity interleaving — so the manual pass below is the one that matters. Run the project's own lint/typecheck/build first, then work through it on a real device, not just a desktop browser.
Build-time
npm run build emits sw.js + manifest.webmanifest (or manifest.json)curl -s localhost:PORT/manifest.webmanifest returns JSON, and the page
HTML actually contains the <link rel="manifest">Offline
The create-then-delete-offline case (the one that breaks every naive implementation): create a row offline, delete it offline, go online. The server must end with zero rows and the client must not resurrect it on the next pull.
Migration
indexedDB reports version N and old rows
carry the new fields.Multi-account (if applicable)
Kill switch
Order matters — each step ships on its own.
offlineApi.getX,
with background revalidation. Ship per screen.try, queueSync in
the catch. At this point the app already survives going offline mid-session./api/sync/changes + /api/sync/push and the flush/pull engine.
Until then the queue accumulates and flushPendingSync no-ops on 404 —
which is a designed state, not a failure.When auditing an app that claims to implement this already, check in this order. These are where the drift actually turns up:
flushPendingSync bulk-clear the queue on HTTP 200?db.version() block that was edited rather than appended?runtimeCaching list cache /api/sync/*?registerType 'autoUpdate'?serverId == null?/changes return tombstones?preferRow (or its equivalent) used by reads as well as by cleanups?What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub vkotaru/agent-skills --plugin web-app-patterns