Progressive Web Apps Integration Guide

Technology: pwa · Category: tooling · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/pwa

Insight:

A PWA is a normal Next.js app plus three pieces: a manifest.ts so it can be installed, a service worker that caches, and a caching strategy chosen per asset. Three things changed the picture by late 2026. Chrome no longer requires a service worker before it will offer an install. iOS 26 opens every site added to the Home Screen as a web app. Lighthouse dropped its PWA category in v12. So "installable" is now cheap, and offline behaviour is where the real engineering goes. For US-first apps that means a fingerprinted precache (Serwist; @serwist/turbopack on Next 16's default builder) and push that iOS supports. For Kenya-targeted apps on 2G/3G it also means an offline outbox for writes. This dashboard is the live reference implementation: a hand-written sw.js whose cache name is stamped with a content hash at build time.

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

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)

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:

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)

Scope comes from the script's location: /sw.js controls the whole origin. Only one worker can control a given scope.

stateDiagram-v2
    [*] --> Registered: navigator.serviceWorker.register('/sw.js')
    Registered --> Installing: parse script
    Installing --> Installed: install event · precache shell
    Installed --> Activating: (skipWaiting skips the wait)
    Activating --> Activated: activate event · purge old caches · clientsClaim
    Activated --> Idle
    Idle --> Fetching: fetch event (any in-scope request)
    Fetching --> Idle: serve from cache / network
    Activated --> [*]: byte-different sw.js found → cycle repeats

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:

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
flowchart TD
    A[Request in scope] --> P{Non-GET, /api/, auth'd<br/>or payment?}
    P -- yes --> N[Network-only<br/>queue idempotent writes in an outbox]
    P -- no --> B{Hash-versioned<br/>JS · CSS · fonts · icons?}
    B -- yes --> C[Cache-first]
    B -- no --> D{HTML page or read API<br/>where freshness matters?}
    D -- yes --> E[Network-first<br/>fallback to cache → /offline]
    D -- no --> F{Occasionally-updated<br/>avatar · thumbnail?}
    F -- yes --> G[Stale-while-revalidate]
    F -- no --> H[Network-only]

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:

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:
"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.
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:

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_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

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

Official docs: