← Back to dashboard

Progressive Web Apps Integration Guide

What is a Progressive Web App?

The real model

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.

Text
██████╗ ██╗    ██╗ █████╗
██╔══██╗██║    ██║██╔══██╗
██████╔╝██║ █╗ ██║███████║
██╔═══╝ ██║███╗██║██╔══██║
██║     ╚███╔███╔╝██║  ██║
╚═╝      ╚══╝╚══╝ ╚═╝  ╚═╝

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:

  1. 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.
  2. 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.
  3. 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)

AreaWasNow (verified 2026-10-20)
Chrome installabilityManifest + HTTPS + service workerManifest + HTTPS + a user-engagement heuristic. No service worker is required (web.dev install criteria)
iOS installOnly sites with a manifest or apple-mobile-web-app-capable opened standaloneiOS/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 pushService-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.js16.3.216.4.2. useOffline is still experimental (import from next/offline)
Serwist9.5.129.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

SourceURLWhat it covers
MDN: Progressive Web Appshttps://developer.mozilla.org/en-US/docs/Web/Progressive_web_appsConcepts, manifest members, guides
web.dev: Service workershttps://web.dev/learn/pwa/service-workersLifecycle (install → activate → fetch), scope
web.dev: Install criteriahttps://web.dev/articles/install-criteriaChrome's exact beforeinstallprompt criteria
Next.js: PWA guidehttps://nextjs.org/docs/app/guides/progressive-web-appsManifest, Web Push with Server Actions, SW headers, useOffline
Next.js: manifest.tshttps://nextjs.org/docs/app/api-reference/file-conventions/metadata/manifestMetadataRoute.Manifest
Serwist: Turbopackhttps://serwist.pages.dev/docs/next/turbo@serwist/turbopack for Next 16's default builder
Serwist: webpackhttps://serwist.pages.dev/docs/next/getting-started@serwist/next + withSerwistInit
Chrome: Caching strategieshttps://developer.chrome.com/docs/workbox/caching-strategies-overviewcache-first / network-first / stale-while-revalidate
MDN: Background Synchttps://developer.mozilla.org/en-US/docs/Web/API/Background_Synchronization_APIregistration.sync.register + sync event (not Baseline)
WebKit: Declarative Web Pushhttps://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)

PackageVersionNotes
next16.4.2Dashboard is on ^16.2.9. Turbopack is the default builder
serwist9.5.13Core worker runtime (Serwist, strategies, BackgroundSyncPlugin)
@serwist/turbopack9.5.13Peers: next >=14, react >=18, esbuild >=0.25 <1
@serwist/next9.5.13webpack plugin. Peers include @serwist/cli ^9.5.13
web-push3.6.7Last published Jan 2024 and still the standard Node sender. engines: node >=16
@types/web-push3.6.4
workbox-*7.4.1Only if you use Workbox directly. Serwist is a Workbox fork
lighthouse13.5.0No 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):

TypeScript
// 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_name or name, icons (including a 192px and a 512px icon), start_url, and display set to one of fullscreen / standalone / minimal-ui / window-controls-overlay.
  • prefer_related_applications is absent or false.

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)

  • install fires once for a new worker. Precache the app shell here (cache.addAll([...])).
  • activate fires when the worker takes control. Delete old caches here. skipWaiting() + clients.claim() let a new worker take over open tabs right away.
  • fetch fires 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):

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.mjs rewrites const 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, and activate purges 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)

StrategyBehaviorUse it for
Cache-firstServe from cache. Go to the network only on a miss, then cache the response.Hash-versioned static assets: /_next/static/*, fonts, icons
Network-firstTry the network. Fall back to the cache when offline (optionally after a timeout).HTML navigations, and read APIs where freshness matters
Stale-while-revalidateServe from cache at once and refresh it in the background.Avatars, thumbnails, content that changes occasionally
Cache-onlyCache only.Precached, versioned shell assets
Network-onlyNetwork 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

Bash
npm i -D @serwist/turbopack@9.5.13 esbuild serwist@9.5.13
JavaScript
// 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/:

TypeScript
// 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

Bash
npm i @serwist/next@9.5.13 && npm i -D serwist@9.5.13
JavaScript
// 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:

TypeScript
/// <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 / BackgroundSyncQueue stores failed requests in IndexedDB. It replays them on sync where that event exists, and when the worker next starts up everywhere else.
  • Also replay from the page on the window online event 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:

  1. Subscribe on the client after a user gesture, never on first load:
TSX
"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
  1. Send from the server with web-push (full helper in examples/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 exports sendPush would let any client trigger pushes.
TypeScript
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;
}
  1. Handle it in the worker: push calls self.registration.showNotification(...), and notificationclick calls self.clients.openWindow(url) (see examples/sw.ts).

Generate the VAPID pair once with npx web-push generate-vapid-keys. The public key isn't secret. The private key is:

VariableSecret?Where
NEXT_PUBLIC_VAPID_PUBLIC_KEYNo (shipped to the browser)Vercel env / .env.local
VAPID_PRIVATE_KEYYesServer env only, via the secrets vault
Bash
VAPID_PRIVATE_KEY=your_vapid_private_key_here

Declarative 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 (localhost already 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

ConcernUS-first defaultKenya-targeted (2G/3G, Android-heavy)
InstallLet the browser promote it. Add a contextual Android button and an iOS hintSame, plus show the value up front ("works offline, uses less data")
NavigationsNetwork-first, fall back to cache → offline pageNetwork-first with a short network timeout (Serwist NetworkFirst({ networkTimeoutSeconds: 3 })), then cache
Static assetsCache-first (/_next/static is hashed)Same. Precache the shell and the 2–3 most-used routes
Read APIsNetwork-only or SWR for public dataStale-while-revalidate for public catalog data (prices, products), with "last updated" shown
WritesOnline only. Show an error when offlineOutbox: queue idempotent writes in IndexedDB and replay on sync / online / app open
PaymentsStripe, online only, never queuedM-Pesa (Daraja), online only. STK Push needs the phone reachable, so queue the order, not the payment
PushOptional re-engagement. iOS needs a Home Screen installUseful for order status. Set a short TTL and a topic so stale updates collapse. SMS/WhatsApp stays the fallback
BundleNormal budgetsTight 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), and components/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.mjs stamps const CACHE = "tech-stack-<hash>" in public/sw.js. If you edit that line by hand, keep the tech-stack- prefix and the exact const CACHE = "…"; shape, or the regex won't match and the stamping silently stops. register-sw.tsx then picks up the new worker on load and on tab focus, and reloads once on controllerchange.
  • 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 CheckoutRequestID and 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_KEY is secret. Send push from server-only code after Clerk auth.
  • Graduate to Serwist once the precached shell grows. Use @serwist/turbopack on Next 16's default builder and @serwist/next only 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.