Progressive Web Apps Integration Guide
What is a Progressive Web App?
Manifest + service worker (install → activate → fetch) + a caching strategy per asset.
The service worker is a network proxy on its own thread. It precaches the app shell at install, then on every fetch picks a strategy: cache-first for versioned JS/CSS, network-first for HTML and APIs (falling back to /offline), stale-while-revalidate for avatars and thumbnails. On Next.js 16 (App Router), generate the manifest with app/manifest.ts and build the worker with Serwist 9.5 (a Workbox fork): @serwist/turbopack for the default Turbopack builder, @serwist/next for webpack. Installing is now easy. Chrome no longer requires a service worker to offer an install, iOS 26 opens every Home Screen site as a web app, and Lighthouse dropped its PWA audit in v12. The real work is offline behaviour. US-first apps need a fingerprinted precache and push. Kenya-targeted 2G/3G apps also need an outbox for writes. This dashboard ships a hand-written sw.js whose cache name is stamped with a content hash on every build.
Six PWA primitives
The web platform pieces that make an app installable, offline-capable, and re-engageable.
██████╗ ██╗ ██╗ █████╗
██╔══██╗██║ ██║██╔══██╗
██████╔╝██║ █╗ ██║███████║
██╔═══╝ ██║███╗██║██╔══██║
██║ ╚███╔███╔╝██║ ██║
╚═╝ ╚══╝╚══╝ ╚═╝ ╚═╝Progressive Web Apps Integration Guide
Focus: make a Next.js 16 app installable and offline-capable. You need a web app manifest so it can be installed, a service worker that caches, the right caching strategy for each asset, and, where it fits, Web Push and an offline outbox for writes. This dashboard is already a PWA, so the patterns below are running in this repo.
Overview
A Progressive Web App is, in MDN's words, "an app that's built using web platform technologies, but that provides a user experience like that of a platform-specific app." It ships like a website, yet users can install it to the home screen, launch it full-screen, and keep using it with no network. Three pieces make that work:
- Web app manifest: a small JSON file with the app's name, icons, colors and launch mode. Browsers read it when they offer an install.
- Service worker: a script that runs on its own thread, outside any page. It intercepts every request in its scope and answers from the cache, the network, or both.
- A caching strategy: the policy the worker applies to each request. Choosing the right strategy for each asset type is most of the work.
What changed since the last review (2026-08-23)
| Area | Was | Now (verified 2026-10-20) |
|---|---|---|
| Chrome installability | Manifest + HTTPS + service worker | Manifest + HTTPS + a user-engagement heuristic. No service worker is required (web.dev install criteria) |
| iOS install | Only sites with a manifest or apple-mobile-web-app-capable opened standalone | iOS/iPadOS 26: every site added to the Home Screen opens as a web app by default. Users can turn off "Open as Web App" (WebKit, Safari 26) |
| iOS push | Service-worker Web Push, Home Screen apps only (16.4+) | Same, plus Declarative Web Push (iOS/iPadOS 18.4+, macOS Safari 18.5), which displays JSON payloads without a service worker |
| Lighthouse | "Run the PWA audit" | The PWA category was removed in Lighthouse v12 (current: 13.5.0). Check installability in DevTools → Application → Manifest instead |
| Next.js | 16.3.2 | 16.4.2. useOffline is still experimental (import from next/offline) |
| Serwist | 9.5.12 | 9.5.13 (10.0.0-preview.14 on the preview tag) |
| Dashboard SW versioning | "Bump the CACHE constant by hand" | scripts/snapshot.mjs stamps CACHE = "tech-stack-<sha256[0..12]>" from the content on every build |
Official Documentation
| Source | URL | What it covers |
|---|---|---|
| MDN: Progressive Web Apps | https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps | Concepts, manifest members, guides |
| web.dev: Service workers | https://web.dev/learn/pwa/service-workers | Lifecycle (install → activate → fetch), scope |
| web.dev: Install criteria | https://web.dev/articles/install-criteria | Chrome's exact beforeinstallprompt criteria |
| Next.js: PWA guide | https://nextjs.org/docs/app/guides/progressive-web-apps | Manifest, Web Push with Server Actions, SW headers, useOffline |
Next.js: manifest.ts | https://nextjs.org/docs/app/api-reference/file-conventions/metadata/manifest | MetadataRoute.Manifest |
| Serwist: Turbopack | https://serwist.pages.dev/docs/next/turbo | @serwist/turbopack for Next 16's default builder |
| Serwist: webpack | https://serwist.pages.dev/docs/next/getting-started | @serwist/next + withSerwistInit |
| Chrome: Caching strategies | https://developer.chrome.com/docs/workbox/caching-strategies-overview | cache-first / network-first / stale-while-revalidate |
| MDN: Background Sync | https://developer.mozilla.org/en-US/docs/Web/API/Background_Synchronization_API | registration.sync.register + sync event (not Baseline) |
| WebKit: Declarative Web Push | https://webkit.org/blog/16535/meet-declarative-web-push/ | Push without a service worker on Apple platforms |
Pinned versions (verified with npm view, 2026-10-20)
| Package | Version | Notes |
|---|---|---|
next | 16.4.2 | Dashboard is on ^16.2.9. Turbopack is the default builder |
serwist | 9.5.13 | Core worker runtime (Serwist, strategies, BackgroundSyncPlugin) |
@serwist/turbopack | 9.5.13 | Peers: next >=14, react >=18, esbuild >=0.25 <1 |
@serwist/next | 9.5.13 | webpack plugin. Peers include @serwist/cli ^9.5.13 |
web-push | 3.6.7 | Last published Jan 2024 and still the standard Node sender. engines: node >=16 |
@types/web-push | 3.6.4 | |
workbox-* | 7.4.1 | Only if you use Workbox directly. Serwist is a Workbox fork |
lighthouse | 13.5.0 | No PWA category since 12.0 |
1. The web app manifest (installability)
In the App Router, generate the manifest with a typed app/manifest.ts. Next serves it at /manifest.webmanifest and injects the <link rel="manifest">. This is the dashboard's manifest (packages/dashboard/app/manifest.ts; full file in examples/manifest.ts):
// app/manifest.ts
import type { MetadataRoute } from "next";
export default function manifest(): MetadataRoute.Manifest {
return {
id: "/", // stable identity across start_url changes
name: "codeAmani Tech-Stack",
short_name: "Tech-Stack",
description: "Interactive developer learning platform.",
start_url: "/",
scope: "/",
display: "standalone",
orientation: "portrait",
background_color: "#0f1115",
theme_color: "#0f1115",
icons: [
{ src: "/icons/icon-192.png", sizes: "192x192", type: "image/png", purpose: "any" },
{ src: "/icons/icon-512.png", sizes: "512x512", type: "image/png", purpose: "any" },
{ src: "/icons/icon-maskable-512.png", sizes: "512x512", type: "image/png", purpose: "maskable" },
],
shortcuts: [{ name: "Search guides", short_name: "Search", url: "/search" }],
};
}Chrome install criteria (web.dev). Chrome fires beforeinstallprompt and shows its own install promotion when all of these hold:
- The app is not already installed.
- The user has clicked or tapped the page at least once, and has viewed it for at least 30 seconds (at any time).
- The page is served over HTTPS.
- The manifest has
short_nameorname,icons(including a 192px and a 512px icon),start_url, anddisplayset to one offullscreen/standalone/minimal-ui/window-controls-overlay. prefer_related_applicationsis absent orfalse.
A service worker is no longer on that list. You still need one for offline support, push and background sync, which are the reasons to build a PWA at all.
iOS / iPadOS 26. Share → Add to Home Screen opens any site as a web app by default, with or without a manifest. If you have a manifest, its icons and settings are still used. iOS never fires beforeinstallprompt, so show a "Share → Add to Home Screen" hint (the dashboard does this in components/pwa/install-prompt.tsx). The Next.js guide advises against a custom beforeinstallprompt button as your only install path because it doesn't work on Safari. On Android, a contextual button still converts well.
2. The service worker (lifecycle: install → activate → fetch)
installfires once for a new worker. Precache the app shell here (cache.addAll([...])).activatefires when the worker takes control. Delete old caches here.skipWaiting()+clients.claim()let a new worker take over open tabs right away.fetchfires for every in-scope request. The worker acts as a network proxy, even when the user is offline.
Scope comes from the script's location: /sw.js controls the whole origin. Only one worker can control a given scope.
Register it from a client component. This is the dashboard's components/pwa/register-sw.tsx, trimmed (full version in examples/register-sw.tsx):
"use client";
import { useEffect } from "react";
export function RegisterServiceWorker() {
useEffect(() => {
if (!("serviceWorker" in navigator)) return;
const hadController = Boolean(navigator.serviceWorker.controller);
let reloading = false;
navigator.serviceWorker.addEventListener("controllerchange", () => {
if (reloading || !hadController) return; // nothing stale on a first visit
reloading = true;
window.location.reload(); // show the new deploy's content once
});
navigator.serviceWorker
.register("/sw.js", { scope: "/", updateViaCache: "none" })
.then((reg) => reg.update()) // re-check now, not in ~24h
.catch(() => {}); // non-fatal: app works without offline
}, []);
return null;
}A browser only installs a new worker when /sw.js is byte-different. So version the cache name in the file itself:
- Dashboard approach:
packages/dashboard/scripts/snapshot.mjsrewritesconst CACHE = "tech-stack-…"to a 12-character SHA-256 of the guide content and changelog on every snapshot. When content changes, the bytes change, the new worker installs, andactivatepurges the old cache. When content doesn't change, the file stays identical and nobody gets a needless reload. - Serwist approach: it injects a revisioned precache manifest at build time, so the worker changes whenever a precached file changes.
3. Caching strategies (choose one per asset)
| Strategy | Behavior | Use it for |
|---|---|---|
| Cache-first | Serve from cache. Go to the network only on a miss, then cache the response. | Hash-versioned static assets: /_next/static/*, fonts, icons |
| Network-first | Try the network. Fall back to the cache when offline (optionally after a timeout). | HTML navigations, and read APIs where freshness matters |
| Stale-while-revalidate | Serve from cache at once and refresh it in the background. | Avatars, thumbnails, content that changes occasionally |
| Cache-only | Cache only. | Precached, versioned shell assets |
| Network-only | Network only. | Non-GET requests, auth'd or per-user data, payments |
Precaching happens at install: a fixed, versioned list of shell files is fetched up front, so the app opens offline on its first relaunch. Runtime caching happens at fetch: responses are cached lazily as the user moves around.
The dashboard's public/sw.js does both. It precaches ["/", "/search", "/browse", "/more", "/offline"], uses network-first for navigations (falling back to the cached page, then /offline), and cache-first for /_next/static/, /icons/ and .webp/.png. Everything else goes straight to the network.
4. Serwist (Next.js 16: Turbopack or webpack)
A hand-written sw.js is fine for a small, fixed shell. Once you precache more than a handful of routes, use Serwist (a maintained fork of Workbox). It builds a revisioned precache manifest at compile time and ships Workbox's strategies as defaultCache. next-pwa (shadowwalker) is unmaintained, so don't use it.
Next 16 builds with Turbopack by default, and @serwist/next is a webpack plugin. Pick the package that matches your builder. The worker source is the same for both; only the defaultCache import differs.
Turbopack path (default builder): @serwist/turbopack
npm i -D @serwist/turbopack@9.5.13 esbuild serwist@9.5.13// next.config.mjs
import { withSerwist } from "@serwist/turbopack";
export default withSerwist({
// your Next.js config
});Serwist serves the compiled worker from a route handler instead of writing it to public/:
// app/serwist/[path]/route.ts
import { spawnSync } from "node:child_process";
import { createSerwistRoute } from "@serwist/turbopack";
// Optional revision for extra precached pages; args passed as an array (no shell).
const revision =
spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf-8" }).stdout ?? crypto.randomUUID();
export const { dynamic, dynamicParams, revalidate, generateStaticParams, GET } = createSerwistRoute({
additionalPrecacheEntries: [{ url: "/~offline", revision }],
swSrc: "app/sw.ts",
useNativeEsbuild: true, // false → esbuild-wasm
});Register it with <SerwistProvider swUrl="/serwist/sw.js"> from @serwist/turbopack/react in app/layout.tsx, in place of a hand-rolled register component. The worker lives under /serwist/, but it still controls the whole site: in 9.5.13 the route handler sends Service-Worker-Allowed: / and the provider registers with scope: "/" by default. If auth middleware guards your app, exclude /serwist/ from it, the same way the dashboard excludes sw.js.
webpack path: @serwist/next
npm i @serwist/next@9.5.13 && npm i -D serwist@9.5.13// next.config.mjs
import { spawnSync } from "node:child_process";
import withSerwistInit from "@serwist/next";
const revision =
spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf-8" }).stdout ?? crypto.randomUUID();
const withSerwist = withSerwistInit({
additionalPrecacheEntries: [{ url: "/~offline", revision }],
swSrc: "app/sw.ts",
swDest: "public/sw.js", // add public/sw* and public/swe-worker* to .gitignore
});
export default withSerwist({
// your Next.js config
});For TypeScript, add "@serwist/next/typings" to compilerOptions.types and "webworker" to lib, and exclude public/sw.js.
The worker (app/sw.ts)
This is a trimmed version of examples/sw.ts, which was type-checked with --strict against serwist@9.5.13:
/// <reference lib="esnext" />
/// <reference lib="webworker" />
import { defaultCache } from "@serwist/next/worker"; // Turbopack: "@serwist/turbopack/worker"
import type { PrecacheEntry, SerwistGlobalConfig } from "serwist";
import { BackgroundSyncPlugin, NetworkOnly, Serwist } from "serwist";
declare global {
interface WorkerGlobalScope extends SerwistGlobalConfig {
__SW_MANIFEST: (PrecacheEntry | string)[] | undefined;
}
}
declare const self: ServiceWorkerGlobalScope;
// Failed POSTs go to IndexedDB and are replayed later (maxRetentionTime is in minutes).
const outbox = new BackgroundSyncPlugin("outbox", { maxRetentionTime: 24 * 60 });
const serwist = new Serwist({
precacheEntries: self.__SW_MANIFEST,
skipWaiting: true,
clientsClaim: true,
navigationPreload: true,
runtimeCaching: [
{
matcher: ({ url, sameOrigin }) => sameOrigin && url.pathname === "/api/outbox",
method: "POST",
handler: new NetworkOnly({ plugins: [outbox] }),
},
...defaultCache, // Workbox-grade defaults per asset type
],
fallbacks: {
entries: [{ url: "/~offline", matcher: ({ request }) => request.destination === "document" }],
},
});
serwist.addEventListeners();5. Offline support
With the shell precached and an offline page as the navigation fallback, a user who loses signal mid-session still sees the app instead of the browser's error page. The dashboard's app/offline/page.tsx is an ordinary route that gets precached. Serwist's examples use /~offline; either name works if you precache it and point the fallback at it. Make sure auth middleware doesn't block it: the dashboard's middleware.ts matcher excludes sw.js, manifest.webmanifest, icons/ and offline from Basic Auth.
useOffline (Next 16, experimental)
useOffline() from next/offline returns true after a request fails or the browser fires offline. It returns false on the server, and always false unless you set experimental: { useOffline: true }. Turning on the flag also makes Next retry blocked navigations, prefetches and Server Action requests when the connection comes back. Use it for connectivity-aware UI (examples/offline-banner.tsx). It is not a cache: it complements a service worker and doesn't replace one. Next's docs say it is not recommended for production yet.
Offline writes: Background Sync and the outbox
Background Sync (registration.sync.register(tag) → a sync event in the worker) is not Baseline: per MDN it only works in some major browsers (Chromium). Don't build a Kenya-critical flow on it alone:
- Serwist's
BackgroundSyncPlugin/BackgroundSyncQueuestores failed requests in IndexedDB. It replays them onsyncwhere that event exists, and when the worker next starts up everywhere else. - Also replay from the page on the window
onlineevent and on app open, so Safari users don't have to wait for a worker restart. - Only queue idempotent writes (send an
Idempotency-Key, and dedupe on the server). Never queue a payment initiation such as an M-Pesa STK Push or a Stripe charge. Queue the order, then start payment online with the user present.
Push notifications (Push API + web-push)
Web Push works in Chromium, Firefox, Safari 16+ on macOS 13+, and on iOS/iPadOS 16.4+ only for Home Screen web apps (not in a Safari tab). The loop:
- Subscribe on the client after a user gesture, never on first load:
"use client";
const registration = await navigator.serviceWorker.ready;
const sub = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY!),
});
await saveSubscription(JSON.parse(JSON.stringify(sub))); // Server Action → DB- Send from the server with
web-push(full helper inexamples/push.ts). Keep the sender in a server-only module that you call from an authenticated Server Action or Route Handler. A"use server"file that exportssendPushwould let any client trigger pushes.
import webpush, { WebPushError } from "web-push";
webpush.setVapidDetails("mailto:dev@example.com", publicKey, privateKey);
try {
await webpush.sendNotification(sub, JSON.stringify({ title, body, url }), {
TTL: 86_400, // hold up to 24h while the phone is offline (default 4 weeks)
urgency: "normal", // very-low | low | normal | high
topic: "order-status" // newer message replaces an undelivered older one
});
} catch (err) {
if (err instanceof WebPushError && (err.statusCode === 404 || err.statusCode === 410)) {
await store.remove(sub.endpoint); // subscription is dead: prune it
} else throw err;
}- Handle it in the worker:
pushcallsself.registration.showNotification(...), andnotificationclickcallsself.clients.openWindow(url)(seeexamples/sw.ts).
Generate the VAPID pair once with npx web-push generate-vapid-keys. The public key isn't secret. The private key is:
| Variable | Secret? | Where |
|---|---|---|
NEXT_PUBLIC_VAPID_PUBLIC_KEY | No (shipped to the browser) | Vercel env / .env.local |
VAPID_PRIVATE_KEY | Yes | Server env only, via the secrets vault |
VAPID_PRIVATE_KEY=your_vapid_private_key_hereDeclarative Web Push (Apple: iOS/iPadOS 18.4+, macOS Safari 18.5+) lets the push service show a notification from a JSON payload ({"web_push": 8030, "notification": {...}}) without running a service worker. Subscription goes through window.pushManager. It's Apple-only for now, so keep the service-worker push handler as the cross-browser path.
Secure the worker's headers
From the Next.js PWA guide, set these in next.config headers() for /sw.js: Cache-Control: no-cache, no-store, must-revalidate, Content-Type: application/javascript; charset=utf-8, and Content-Security-Policy: default-src 'self'; script-src 'self'. Add X-Content-Type-Options: nosniff site-wide. (The dashboard doesn't set these today. It relies on updateViaCache: "none" + reg.update() and the host's defaults; see NOTES.)
Testing
- Local HTTPS:
next dev --experimental-https(localhostalready counts as a secure context for plain SW registration). - Installability: Chrome DevTools → Application → Manifest (shows install errors) and → Service workers / Cache storage. Lighthouse has no PWA category since v12.
- Offline: DevTools → Network → Offline, or Application → Service workers → Offline. Then navigate to an uncached route and confirm the fallback appears.
- Slow networks: throttle to "Slow 3G"/"3G" for the Kenya-targeted profile and check that a repeat visit makes almost no network requests.
- iOS: Safari 26+ Develop menu → Inspect Apps and Devices → "Automatically Inspect New Service Workers" to catch push handlers as they run.
6. US-first defaults vs Kenya-targeted offline profile
| Concern | US-first default | Kenya-targeted (2G/3G, Android-heavy) |
|---|---|---|
| Install | Let the browser promote it. Add a contextual Android button and an iOS hint | Same, plus show the value up front ("works offline, uses less data") |
| Navigations | Network-first, fall back to cache → offline page | Network-first with a short network timeout (Serwist NetworkFirst({ networkTimeoutSeconds: 3 })), then cache |
| Static assets | Cache-first (/_next/static is hashed) | Same. Precache the shell and the 2–3 most-used routes |
| Read APIs | Network-only or SWR for public data | Stale-while-revalidate for public catalog data (prices, products), with "last updated" shown |
| Writes | Online only. Show an error when offline | Outbox: queue idempotent writes in IndexedDB and replay on sync / online / app open |
| Payments | Stripe, online only, never queued | M-Pesa (Daraja), online only. STK Push needs the phone reachable, so queue the order, not the payment |
| Push | Optional re-engagement. iOS needs a Home Screen install | Useful for order status. Set a short TTL and a topic so stale updates collapse. SMS/WhatsApp stays the fallback |
| Bundle | Normal budgets | Tight budgets: lazy-load below the fold, no web fonts on the offline page |
codeAmani notes
- This dashboard is the reference implementation. Read the repo before reaching for a tutorial:
app/manifest.ts,public/sw.js,app/offline/page.tsx,lib/pwa.ts,middleware.ts(excludes the PWA shell files from Basic Auth), andcomponents/pwa/(register-sw.tsx,install-prompt.tsx,ios-app-shell.tsx,ios-tab-bar.tsx). It precaches the shell, uses network-first for navigations and cache-first for static assets, and handles both the Chrome install prompt and the iOS Share-sheet hint. - Don't hand-bump the dashboard's cache name.
scripts/snapshot.mjsstampsconst CACHE = "tech-stack-<hash>"inpublic/sw.js. If you edit that line by hand, keep thetech-stack-prefix and the exactconst CACHE = "…";shape, or the regex won't match and the stamping silently stops.register-sw.tsxthen picks up the new worker on load and on tab focus, and reloads once oncontrollerchange. - US-first by default: payments are Stripe, online only. A PWA doesn't change the payment rail. Never cache or queue checkout/session calls.
- Kenya-targeted projects: offline-first is the baseline, not polish. Add the outbox pattern (§5) and network timeouts (§6). Use M-Pesa (Daraja) for payments, always online, and never replay an STK Push from a queue (store
CheckoutRequestIDand dedupe callbacks as usual). - HTTPS is non-negotiable, and Vercel/Cloudflare provide it for free, including preview URLs.
- Never cache per-user or auth'd responses in the service worker cache. It's shared and not keyed by user. Let
/api/*and Clerk-protected data fall through to the network. - Keep secrets server-side. Only
VAPID_PRIVATE_KEYis secret. Send push from server-only code after Clerk auth. - Graduate to Serwist once the precached shell grows. Use
@serwist/turbopackon Next 16's default builder and@serwist/nextonly if you build with webpack. - Don't cite Lighthouse PWA scores in reviews or client reports. The category is gone, so use the DevTools Application panel and a manual offline test instead.