Panduan Full Stack Engineer: Konfigurasi PWA Offline-First dengan @serwist/next di Next.js 16 App Router & React 19
Spesialisasi Rekayasa Perangkat Lunak: Ditulis oleh Aldian Fazrihady — Senior Cloud Engineer, GCP Professional Cloud Architect, GCP Professional Data Engineer, Backend Engineer, AI Application Engineer & Full Stack Engineer.
1. Mengapa Migrasi dari next-pwa ke @serwist/next Wajib untuk Next.js 15/16 App Router?
Dalam pengembangan aplikasi web modern menggunakan Next.js 16 App Router dan React 19, pustaka lama berbasis Workbox seperti next-pwa sering gagal melakukan precaching pada payload React Server Components (RSC) dan memicu loop pembaruan Service Worker.Sebagai Full Stack Engineer, menggunakan @serwist/next memungkinkan kompilasi app/sw.ts secara type-safe dengan strategi caching NetworkFirst untuk navigasi RSC dan StaleWhileRevalidate untuk aset statis.
2. Konfigurasi next.config.mjs, tsconfig.json, dan Lifecycle Service Worker
Agar compiler TypeScript mengenali global ServiceWorkerGlobalScope tanpa berkonflik dengan DOM tipe React 19, tambahkan "webworker" pada lib di tsconfig.json dan kecualikan public/sw.js. Di bawah ini adalah kode konfigurasi produksi lengkap untuk @serwist/next bersama Next.js 16 dan React 19:
npm install @serwist/next @serwist/window
npm install -D serwist
// next.config.ts
import type { NextConfig } from "next";
import withSerwistInit from "@serwist/next";
const withSerwist = withSerwistInit({
swSrc: "src/app/sw.ts", // Path to our custom TypeScript service worker
swDest: "public/sw.js", // Where the compiled service worker will be output
register: false, // Disables auto-registration (we will register manually)
});
const nextConfig: NextConfig = {
output: "standalone", // Ideal for containerized cloud environments (e.g., Cloud Run)
outputFileTracingRoot: __dirname,
};
export default withSerwist(nextConfig);
// src/app/sw.ts
import { defaultCache } from "@serwist/next/worker";
import type { PrecacheEntry, SerwistGlobalConfig } from "serwist";
import { Serwist, NetworkOnly } from "serwist";
// 1. Declare strictly typed ServiceWorker global scope
declare global {
interface WorkerGlobalScope extends SerwistGlobalConfig {
__SW_MANIFEST: (PrecacheEntry | string)[] | undefined;
}
}
declare const self: ServiceWorkerGlobalScope;
// 2. SOLVING THE FIREBASE OFFLINE GOTCHA:
// If you are using Firebase Auth, Firestore, or RTDB, you MUST exclude their API requests
// from the Service Worker caching. Caching Firestore's websocket / polling channels
// breaks Firestore's native offline synchronization.
const customCache = [
{
matcher: ({ url }: { url: URL }) =>
url.hostname.includes("firestore.googleapis.com") ||
url.hostname.includes("google.com"),
handler: new NetworkOnly(), // Never intercept or cache Firestore/Google accounts requests
},
...defaultCache,
];
const serwist = new Serwist({
precacheEntries: self.__SW_MANIFEST,
skipWaiting: false, // Do NOT force immediate activation; wait for user confirmation
clientsClaim: true,
// 3. BYPASSING THE NAVIGATION PRELOAD REJECTION BUG:
// Enabling navigationPreload in custom middleware / proxy configurations can trigger
// fetch event promise rejection crashes on initial redirects. Keep it disabled.
navigationPreload: false,
runtimeCaching: customCache as unknown as NonNullable<
ConstructorParameters<typeof Serwist>[0]
>["runtimeCaching"],
});
// Explicitly handle update messages sent by the client interface
self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});
serwist.addEventListeners();
// src/components/PwaUpdater.tsx
"use client";
import { useEffect, useState } from "react";
export function PwaUpdater() {
const [showPrompt, setShowPrompt] = useState(false);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const [serwistInstance, setSerwistInstance] = useState<any>(null);
useEffect(() => {
// 1. Defend against non-browser contexts and automation runners
if (
typeof window !== "undefined" &&
"serviceWorker" in navigator &&
!navigator.webdriver
) {
// 2. Asynchronously load Serwist window module to optimize initial TBT/LCP scores
import("@serwist/window").then(({ Serwist }) => {
const serwist = new Serwist("/sw.js", { scope: "/", type: "classic" });
setSerwistInstance(serwist);
// 3. Trigger alert when a new update is waiting in the background
serwist.addEventListener("waiting", () => {
setShowPrompt(true);
});
// 4. Force reload ONLY when the new SW successfully takes control
serwist.addEventListener("controlling", () => {
window.location.reload();
});
const promise = serwist.register();
if (promise && typeof promise.catch === "function") {
promise.catch((err: unknown) => {
console.warn("Service worker registration failed or was blocked:", err);
});
}
});
}
}, []);
const handleUpdate = () => {
setShowPrompt(false); // Immediate visual cleanup
if (serwistInstance) {
// Send the skipWaiting message which resolves the waiting SW and triggers "controlling"
serwistInstance.messageSkipWaiting();
}
};
if (!showPrompt) return null;
return (
<div className="fixed bottom-4 right-4 z-50 bg-blue-600 text-white px-6 py-4 rounded-lg shadow-xl flex flex-col sm:flex-row items-center gap-4 animate-in fade-in slide-in-from-bottom-4">
<p className="m-0 font-medium">A new version of the app is available!</p>
<button
onClick={handleUpdate}
className="bg-white text-blue-600 px-4 py-2 rounded font-bold hover:bg-gray-100 transition-colors cursor-pointer"
>
Update Now
</button>
</div>
);
}
// src/app/[lang]/layout.tsx
import { PwaUpdater } from "@/components/PwaUpdater";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<main>{children}</main>
{/* Dynamic, non-blocking service worker manager */}
<PwaUpdater />
</body>
</html>
);
}
Ringkasan Arsitektur Produksi & Praktik Terbaik (Checklist Teknis)
- Keandalan & Observabilitas Produksi: Setiap implementasi wajib dilengkapi metrik latensi P50/P95/P99, penanganan kegagalan idempoten, dan pengujian otomatis di CI/CD.
- Keamanan & Isolasi Least-Privilege: Validasi seluruh input eksternal, gunakan enkripsi standar industri, dan terapkan prinsip hak akses minimum pada layanan cloud maupun penyimpanan lokal.
- Konsultasi & Implementasi 1 Hari: Butuh bantuan mengimplementasikan arsitektur ini di sistem produksi Anda? Pesan Layanan Pemrograman 1 Hari (Rp 1.000.000 via QRIS / Virtual Account atau $100 USD) atau hubungi melalui Upwork.