Next.js Progressive Web Apps: Manifest to Install
A Progressive Web App is not a different framework â it is a checklist the browser evaluates: a valid web app manifest, a service worker with a fetch handler, and an HTTPS origin. Meet all three and Chrome, Edge, and Safari surface the install prompt, the app launches in its own window without browser chrome, and cached assets keep the shell alive on a subway ride with no signal. Miss one and the features silently never appear, which is why PWA work in Next.js fails more often from configuration drift than from missing technology.
This lesson assembles a production PWA on the App Router: the manifest and icons, a Workbox-powered service worker that caches deliberately rather than aggressively, an offline fallback page, update flows that do not trap users on stale bundles, and a push notification pipeline that respects browser permission UX. Along the way it covers the testing checklist that proves each piece works â because an install prompt that never appears and a cache strategy that never hits are both invisible failures until someone opens the browser's application panel.
Prerequisites
- !Comfort editing next.config and the app directory
- !Understanding of HTTP caching basics
- !A deployed HTTPS origin to test install behavior
What You'll Learn
- 1Configure next-pwa or Serwist to emit a service worker
- 2Write a manifest that satisfies installability checks on major browsers
- 3Design cache strategies per asset type instead of caching everything
- 4Register and handle web push subscriptions safely
The manifest: your app's identity card
The manifest tells the browser what the installed app looks like: name, short name, theme colors, display mode, and the icon set the launcher will use. The short_name is what fits under the icon on a home screen; the name appears in the app switcher. Provide at least a 192 and a 512 pixel icon, plus a maskable variant so Android can shape the icon without cropping your logo.
{
"name": "Field Notes â Offline Journal",
"short_name": "FieldNotes",
"description": "Capture notes that sync when you reconnect.",
"start_url": "/",
"scope": "/",
"display": "standalone",
"orientation": "portrait",
"background_color": "#0f172a",
"theme_color": "#2563eb",
"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": "New note",
"url": "/notes/new",
"icons": [{ "src": "/icons/shortcut-new.png", "sizes": "96x96" }]
}
]
}
Link it from the root layout's metadata so every page declares it without manual head tags. display: standalone removes the browser UI; some products prefer minimal-ui when users still need a refresh control during development.
Generating the service worker
next-pwa wraps your config and emits a precache manifest built from the production bundle. The runtime caching section is where the real decisions live: static Next.js assets get a cache-first strategy with long lifetimes, navigation requests get a network-first approach with an offline fallback, and API calls generally should not be cached at all unless you have explicitly designed for staleness.
// next.config.js
const withPWA = require('next-pwa')({
dest: 'public',
register: true,
skipWaiting: true,
disable: process.env.NODE_ENV === 'development',
runtimeCaching: [
{
urlPattern: /^_next\/static\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'next-static',
expiration: { maxEntries: 200, maxAgeSeconds: 60 * 60 * 24 * 365 },
},
},
{
urlPattern: /^\/(?:_next\/image\?url=).*/i,
handler: 'CacheFirst',
options: {
cacheName: 'next-images',
expiration: { maxEntries: 300, maxAgeSeconds: 60 * 60 * 24 * 30 },
},
},
{
urlPattern: ({ url }) => url.pathname.startsWith('/api/'),
handler: 'NetworkOnly',
},
{
urlPattern: ({ request }) => request.mode === 'navigate',
handler: 'NetworkFirst',
options: {
cacheName: 'pages',
expiration: { maxEntries: 50, maxAgeSeconds: 60 * 60 * 24 * 7 },
networkTimeoutSeconds: 3,
},
},
],
});
module.exports = withPWA({
// your existing Next.js config
});
NetworkFirst for navigations gives users the fresh page when online and a recent copy when not, with the timeout preventing a dead network from hanging the request for thirty seconds. NetworkOnly for the API keeps personalized data out of a shared cache â an offline note app should queue writes locally, not serve another user's responses.
An offline fallback the user understands
When a navigation request fails and the cache has nothing, the browser shows its own dinosaur page. Replace it with a branded fallback that explains the situation and, ideally, offers the offline-capable parts of the app.
// app/offline/page.js
export default function OfflinePage() {
return (
<main className="offline">
<h1>You are offline</h1>
<p>
This page has not been cached yet. Your saved notes are still available
from the home screen.
</p>
<a href="/">Go to saved notes</a>
</main>
);
}
With next-pwa, pointing the navigation handler's offlineFallback option at this route wires it up. The page itself must be included in the precache manifest so it loads without a network.
Registration done right
Registration should start after load so the service worker never competes with first paint, and it should be wrapped so a browser without support or a user who has cleared storage does not throw unhandled rejections.
// components/RegisterSW.js
'use client';
import { useEffect } from 'react';
export function RegisterSW() {
useEffect(() => {
if (
process.env.NODE_ENV === 'production' &&
'serviceWorker' in navigator
) {
window.addEventListener('load', () => {
navigator.serviceWorker
.register('/sw.js', { scope: '/' })
.catch((err) => {
console.error('Service worker registration failed', err);
});
});
}
}, []);
return null;
}
Mount it in the root layout. Keep the development disable in place â an active service worker during local iteration is the classic cause of pages that refuse to show your latest CSS change.
Ship updates users actually receive
Deploying a change to a service worker is only the beginning; getting installed clients onto the new worker is where PWAs get notoriously fiddly. Browsers refetch the worker script on navigation and compare bytes, so a worker whose file content changed installs in the background â but it waits in the waiting state until every tab controlled by the old worker closes, or until the new worker calls skipWaiting. next-pwa sets skipWaiting by default, which accelerates the swap but opens the compatibility window: a tab still running the old page's JavaScript may talk to a worker serving new precache assumptions.
The coordination tool is the message handshake. On controllerchange, reload the page once so the document and the worker agree on versions, guarded by a flag so the reload happens a single time rather than looping. Pair that with a visible prompt instead of a silent reload when the user is mid-form â updating out from under someone typing a credit card number is the kind of polish failure that erases trust in the install prompt.
Version the precache manifest on every build as well. Filenames under the static path already carry content hashes, so entries swap cleanly, but your own runtime cache names should include a build identifier so a major strategy change does not inherit buckets filled under the old rules. An explicit cleanup pass in the activate handler that deletes cache names outside the current version list is the standard guard against storage bloat on long-lived installs.
Push notifications without being annoying
Web push has three moving parts: the browser's permission prompt, a subscription object stored per user on your server, and a push service (often the operating system's) that delivers messages even when the tab is closed. Ask for permission in response to a clear user gesture, never on first load; the prompt is a one-shot resource and a premature ask earns a permanent block.
// lib/push.js
export async function saveSubscription(userId, subscription) {
await db.pushSubscriptions.upsert({
where: { userId },
create: { userId, endpoint: subscription.endpoint, data: subscription },
update: { data: subscription },
});
}
export async function sendPush(userId, payload) {
const sub = await db.pushSubscriptions.findUnique({ where: { userId } });
if (!sub) return;
await webpush.sendNotification(
sub.data,
JSON.stringify(payload),
{ vapidKeys: process.env.VAPID_KEYS, TTL: 60 * 60 * 24 }
);
}
Store VAPID keys as environment secrets, set a TTL so undeliverable notifications expire instead of flooding a reconnected device, and delete subscriptions whose endpoints return 410 Gone â the push service tells you explicitly when a subscription is dead.
Testing the checklist
Use the browser's application panel: the manifest parses without errors, the service worker activates, and the installability audit passes. Test offline by toggling the network, not by assuming the cache strategy works â the precache list and the runtime cache names are visible in the cache storage view. On iOS, add to home screen manually since Safari's install prompt rules differ; verify the standalone display and status bar styling on a real device.
Common Mistakes
Leaving the service worker active in development
Fix: Disable next-pwa outside production; stale caches will hide your changes for an entire debugging session.
Caching API responses with a generic strategy
Fix: Mark authenticated endpoints NetworkOnly, or design explicit offline queues with user-scoped cache keys.
Asking for notification permission on first load
Fix: Trigger the prompt from a meaningful action such as enabling daily reminders in settings.
Shipping only a 512 pixel icon
Fix: Provide 192, 512, and a maskable variant; the install audit and launcher crop behavior require the set.
Best Practices
- Choose cache strategies per asset class rather than one global rule
- Version the service worker on every deploy so updates propagate predictably
- Queue offline writes in IndexedDB and replay them when connectivity returns
- Prune push subscriptions that the push service marks as gone
Interview Questions
Q1: What three conditions make a Next.js app installable?
A valid web app manifest linked from the page, a registered service worker with a fetch handler, and an HTTPS origin.
Q2: Why is NetworkFirst appropriate for navigations?
Users get the fresh HTML when online, and the cache supplies a recent copy within a short network timeout when offline.
Q3: Why defer service worker registration until after load?
Early registration competes with first-paint resources and can delay the very performance the app is meant to keep.
Key Takeaways
- Installability is a checklist: manifest, service worker, HTTPS â verify all three.
- Manifest icons need 192, 512, and maskable variants for modern launchers.
- Runtime caching must be designed per asset class; blanket caching breaks authenticated data.
- Disable the worker in development to keep caches from hiding changes.
- Push notifications require a user gesture, stored subscriptions, and pruning of dead endpoints.