Full Stack Engineer: Membangun Progressive Web App (PWA) Offline-First dengan Next.js 15, Service Worker & Sinkronisasi IndexedDB
Tim teknisi lapangan, tablet medis di rumah sakit, serta pemindai logistik gudang sering beroperasi di area dengan sinyal seluler dan Wi-Fi yang tidak stabil. Aplikasi web standar akan gagal saat jaringan terputus dan menghilangkan data formulir yang sedang diisi pengguna. Sebagai Full Stack Engineer, saya merancang Progressive Web App (PWA) Offline-First di Next.js 15 dan React 19 menggunakan Service Worker, outbox mutasi lokal di IndexedDB, serta rekonsiliasi Background Sync API.
1. Outbox Mutasi Lokal IndexedDB & Status Penyimpanan Draf yang Akurat
Alih-alih menampilkan indikator "Draf tersimpan" palsu saat komponen baru dimuat sebelum ada perubahan data, pengelola state offline-first kami hanya mencatat waktu penyimpanan setelah perubahan pengguna benar-benar tersimpan di dalam penyimpanan objek IndexedDB (pending_mutations), lalu menyiapkan amplop sinkronisasi ber-Idempotency-Key untuk dikirim saat jaringan kembali aktif:
export interface QueuedMutation {
mutationId: string;
endpoint: string;
payload: Record<string, unknown>;
clientUpdatedAtIso: string;
}
export async function enqueueOfflineMutation(
db: IDBDatabase,
mutation: QueuedMutation
): Promise<void> {
return new Promise((resolve, reject) => {
const tx = db.transaction(["pending_mutations"], "readwrite");
const store = tx.objectStore("pending_mutations");
store.put(mutation);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
export async function flushOfflineMutations(db: IDBDatabase): Promise<number> {
const tx = db.transaction(["pending_mutations"], "readonly");
const store = tx.objectStore("pending_mutations");
const all: QueuedMutation[] = await new Promise((res, rej) => {
const req = store.getAll();
req.onsuccess = () => res(req.result as QueuedMutation[]);
req.onerror = () => rej(req.error);
});
let synced = 0;
for (const item of all) {
const resp = await fetch(item.endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Idempotency-Key": item.mutationId,
},
body: JSON.stringify(item.payload),
});
if (resp.ok || resp.status === 409) {
const delTx = db.transaction(["pending_mutations"], "readwrite");
delTx.objectStore("pending_mutations").delete(item.mutationId);
synced += 1;
}
}
return synced;
}
2. Caching Service Worker & Rekonsiliasi Bebas Duplikasi
Bundel statis _next/static/ disimpan di cache dengan hash konten permanen, sementara pembacaan API menerapkan strategi NetworkFirst dengan fallback ke snapshot IndexedDB saat offline. Saat perangkat kembali terhubung ke internet, Service Worker mengirimkan antrean mutasi ke backend PostgreSQL idempoten dan API Next.js 15 & Django Ninja. Kunjungi Layanan Sprint Teknik 1 Hari untuk membangun aplikasi PWA Anda.