What You'll Learn
- 1Explain what the browser checks before it offers an install prompt
- 2Choose a Workbox strategy for each class of request and justify the choice
- 3Version a precache so a deploy never leaves users on a broken old bundle
- 4Request notification permission at a moment where refusal does not break the feature
A progressive web app is not a feature you add; it is a set of behaviours the browser can verify. The page loads over a secure connection, a manifest describes how the icon should look when installed, and a service worker answers at least one network request while the page is offline. Get those three right and the browser offers an install prompt and treats the app like a native one. Get the service worker subtly wrong and you inherit the worst failure mode in web development: a client that keeps rendering last week's bundle with no visible way to refresh it.
What the install prompt actually requires
Chrome and its derivatives look for a manifest with a name, icons including a maskable 512 pixel variant, a start URL, and a display mode of standalone or minimal UI, plus a service worker with a fetch handler. The icons requirement is where most teams stall, because a 192 pixel icon that merely scales up from the logo looks broken on a home screen and the browser rejects it. iOS does not use the manifest at all and instead reads Apple touch icon tags, which is why a real cross-platform check includes an iPhone home screen and not just the Chrome prompt.
| Requirement | Why it exists | Symptom when missing |
|---|---|---|
| HTTPS or localhost | Protects the installed app surface | No service worker registration at all |
| Manifest with name and icons | Gives the launcher a face | Install prompt never appears |
| Fetch handler in the worker | Proves offline behaviour exists | Prompt may appear, offline still fails |
| Display standalone | Hides the browser chrome | Opens in a tab instead of a window |
| Service worker over an idle scope | Isolates the app from other scripts | Assets resolve to the wrong scope |
The lifecycle you are actually managing
A service worker is a programmable cache proxy that the browser installs once and then runs independently of any page. Installation precaches assets and fires regardless of whether a tab is open. Activation runs after every old worker has released its clients, which is the gap that makes deploys confusing: a new worker can be installed and waiting while three open tabs still run the old code, and clicking reload in one of them does not necessarily take you to the new version.
// src/registerServiceWorker.js
export function registerServiceWorker() {
if (!('serviceWorker' in navigator)) return;
window.addEventListener('load', () => {
navigator.serviceWorker
.register('/sw.js', { scope: '/' })
.then((registration) => {
registration.addEventListener('updatefound', () => {
const next = registration.installing;
if (!next) return;
next.addEventListener('statechange', () => {
if (next.state === 'installed' && navigator.serviceWorker.controller) {
window.dispatchEvent(new CustomEvent('sw-update-ready'));
}
});
});
})
.catch((error) => console.error('Registration failed', error));
});
let refreshing = false;
navigator.serviceWorker.addEventListener('controllerchange', () => {
if (refreshing) return;
refreshing = true;
window.location.reload();
});
}
The controllerchange listener is the piece people omit. Without it, a user who accepts an update by reloading the page keeps the old document and the new worker never controls it, so the update appears not to work. Guard the reload with a flag so a worker that activates twice cannot loop the page.
Caching strategy is a decision per request class
There is no single correct policy. Static build assets are content-hashed, so they never change and cache-first is strictly right. A document request should revalidate so a deploy lands quickly. Account and payment endpoints must never be cached at all, because showing a stale balance is a correctness bug that looks like a security one. Workbox lets you express exactly that with a route and a strategy.
// public/sw.js
import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
import { registerRoute, setCatchHandler } from 'workbox-routing';
import { CacheFirst, NetworkFirst, StaleWhileRevalidate } from 'workbox-strategies';
import { ExpirationPlugin } from 'workbox-expiration';
precacheAndRoute(self.__WB_MANIFEST);
cleanupOutdatedCaches();
registerRoute(
({ request }) => request.destination === 'style' || request.destination === 'script',
new CacheFirst({ cacheName: 'static-assets' })
);
registerRoute(
({ url }) => url.pathname.startsWith('/api/catalog'),
new NetworkFirst({
cacheName: 'catalog',
networkTimeoutSeconds: 3,
plugins: [new ExpirationPlugin({ maxEntries: 60, maxAgeSeconds: 86400 })],
})
);
registerRoute(
({ url }) => url.pathname.startsWith('/api/me'),
() => Response.error()
);
setCatchHandler(async ({ request }) => {
if (request.mode === 'navigate') {
return caches.match('/offline.html');
}
return Response.error();
});
Read the table of strategies the way you would read a decision record. Cache first trades freshness for speed and is safe only when the URL changes on every change of content. Network first with a timeout gives online users the truth and offline users a recent copy, at the cost of a slow first paint on a bad connection. Stale while revalidate is the compromise for things like avatars, where the old copy is good enough for a second while the new one downloads.
| Strategy | Serves | Best for | Never for |
|---|---|---|---|
| CacheFirst | Cache until it expires | Hashed bundles, fonts, images | Anything user-specific |
| NetworkFirst | Network, cache on failure | Read-heavy API routes with a timeout | Large streaming payloads |
| StaleWhileRevalidate | Cache immediately, refresh after | Catalog data, thumbnails | Data where a stale value is dangerous |
| NetworkOnly | Network, error if offline | Payments, auth, logout | Static assets |
| Composed from the above | Varies by request | Mixed applications | Requests you have not classified |
Precaching without stranding users on old bundles
The precache manifest that a bundler emits lists every asset with a revision hash, so the worker fetches the new set during install and keeps the old one until activation. Two things go wrong in practice. The first is a bundle that references a lazy chunk which is no longer in the manifest, producing a failed fetch at the moment a user navigates to a rarely used screen â the fix is to precache every emitted chunk rather than only the entry points. The second is a stale cache that grows forever, which is what cleanupOutdatedCaches and a bounded expiration plugin exist to prevent.
Skip a temptation while you are there: calling skipWaiting unconditionally inside the install handler makes the new worker take over a page that is still executing the old bundle, and any dynamic import the page requests afterwards will 404. Update prompts belong in the interface, where the user chooses when to reload.
Push notifications without begging for permission
Notification permission is requested once per origin and remembered forever, including the refusal. Asking on first load converts a curious visitor into a permanent no. The pattern that works is to trigger the prompt from an explicit control such as a subscribe button on a notifications settings page, after the value is obvious, and to handle the denied state by offering an in-app inbox instead of an unexplained silent failure.
import { useEffect, useState } from 'react';
export function NotificationSettings() {
const [permission, setPermission] = useState(Notification.permission);
useEffect(() => {
if (!('serviceWorker' in navigator)) return undefined;
let cancelled = false;
navigator.serviceWorker.ready.then((registration) => {
if (cancelled) return;
registration.pushManager.getSubscription().then((existing) => {
if (existing) setPermission('granted');
});
});
return () => {
cancelled = true;
};
}, []);
async function subscribe() {
const result = await Notification.requestPermission();
setPermission(result);
if (result !== 'granted') return;
const registration = await navigator.serviceWorker.ready;
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY,
});
await fetch('/api/push/subscribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(subscription),
});
}
return (
<section>
<h2>Notifications</h2>
{permission === 'denied' && (
<p>Notifications are blocked in your browser settings.</p>
)}
{permission === 'default' && (
<button type="button" onClick={subscribe}>
Enable notifications
</button>
)}
{permission === 'granted' && <p>Notifications are on.</p>}
</section>
);
}
Two rules govern the payloads themselves. Every push must open a meaningful view when clicked, because a notification that dismisses into nothing trains users to ignore the next one, and the service worker should handle notificationclick by focusing an existing window rather than opening a new tab on every tap. The subscription you store is per device and expires without warning, so treat a rejected push as a signal to delete the record rather than retrying forever.
Debugging a worker that will not update
Service worker bugs are cache bugs, and caches outlive every other debugging step. The network panel with service workers bypassed shows the truth about the server, while the cache storage panel shows what users actually get. Unregister the worker and clear the cache together; doing only one leaves the illusion of a fix. In development, registering a worker at all is usually a mistake â a precached shell will keep serving your in-progress source until you hard reload, which is time nobody plans to spend.
Version the cache names with the build id when you need a hard reset, and add a kill switch in the worker that fetches a remote flag during activation and unregisters itself if the flag says the release is bad. Ship that before you need it, because the alternative is asking every installed client to clear site data by hand.
Common Mistakes
Caching authenticated API responses with a cache-first policy
Fix: Classify every route and force account, payment and logout traffic to network only
Calling skipWaiting and clientsClaim so the update applies under the user's feet
Fix: Let the new worker wait and offer the reload through an update prompt in the UI
Requesting notification permission on first load
Fix: Ask from an explicit subscribe control after the value of subscribing is clear
Forgetting to precache lazy chunks so rarely visited routes fail offline
Fix: Precache the whole build manifest and keep a navigation fallback page
Best Practices
- Serve the app over HTTPS and verify the manifest icons at real device sizes
- Give every cache a name that includes the build version and clean up outdated entries
- Show an offline fallback for navigations and a clear error for failed API calls
- Treat a failed push as a signal to delete the stored subscription
- Bypass the service worker during local development unless you are testing it
Key Takeaways
- Installability requires a manifest with real icons and a worker with a fetch handler, not just an add-to-homescreen button
- Caching strategy is chosen per request class: hashed assets cache first, user data never caches
- Deploys are a two-phase problem, and an unconditional skipWaiting breaks the running bundle
- Push permission is a one-time decision, so ask when the user already wants the feature
- Debugging means bypassing the worker and clearing storage together, or the stale copy survives