web-pwa — Progressive Web App Patterns for Next.js
1. When to Build a PWA (and When Native Is Better)
Build a PWA when:
- Your core value works in a browser (forms, dashboards, content, e-commerce)
- You need installability but not deep OS integration
- Offline reading, caching, or background sync is sufficient
- You want one codebase across desktop, Android, and iOS
- App store distribution overhead is not worth it
Choose native when:
- You need Bluetooth, NFC, USB, or ARKit/ARCore
- You need background audio/location that runs even when the screen is off
- Your app is heavily gesture-driven (swipe-heavy games, camera apps)
- iOS restrictions matter: WebKit blocks service workers in WKWebView; Apple's PWA support lags Chromium
- You need in-app purchase with App Store billing
PWA support caveats (2024):
- iOS 16.4+ supports push notifications for PWAs installed to home screen only
- Safari blocks persistent storage without user gesture
- Background sync is Chromium-only (no Safari, limited Firefox)
2. Web App Manifest
/public/manifest.json
json
{
"name": "My App — Full Name",
"short_name": "MyApp",
"description": "What your app does in one sentence.",
"start_url": "/?source=pwa",
"display": "standalone",
"orientation": "portrait-primary",
"background_color": "#ffffff",
"theme_color": "#1a1a2e",
"categories": ["productivity", "utilities"],
"lang": "en-US",
"icons": [
{
"src": "/icons/icon-192x192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any"
},
{
"src": "/icons/icon-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any"
},
{
"src": "/icons/icon-maskable-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
],
"shortcuts": [
{
"name": "New Entry",
"short_name": "New",
"description": "Create a new entry",
"url": "/new?source=shortcut",
"icons": [{ "src": "/icons/shortcut-new.png", "sizes": "96x96" }]
},
{
"name": "Dashboard",
"short_name": "Dashboard",
"url": "/dashboard?source=shortcut",
"icons": [{ "src": "/icons/shortcut-dashboard.png", "sizes": "96x96" }]
}
],
"screenshots": [
{
"src": "/screenshots/desktop.png",
"sizes": "1280x720",
"type": "image/png",
"form_factor": "wide",
"label": "Dashboard view on desktop"
},
{
"src": "/screenshots/mobile.png",
"sizes": "390x844",
"type": "image/png",
"form_factor": "narrow",
"label": "Dashboard view on mobile"
}
],
"related_applications": [],
"prefer_related_applications": false
}
Link manifest in app/layout.tsx
tsx
// app/layout.tsx
import type { Metadata } from 'next'
export const metadata: Metadata = {
manifest: '/manifest.json',
themeColor: '#1a1a2e',
appleWebApp: {
capable: true,
statusBarStyle: 'default',
title: 'MyApp',
},
formatDetection: {
telephone: false,
},
}
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
{/* iOS home screen icons — manifest icons don't apply on Safari */}
<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png" />
<link rel="apple-touch-icon" sizes="152x152" href="/icons/icon-152x152.png" />
<link rel="apple-touch-icon" sizes="180x180" href="/icons/icon-180x180.png" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
<meta name="apple-mobile-web-app-title" content="MyApp" />
{/* Microsoft Tiles */}
<meta name="msapplication-TileColor" content="#1a1a2e" />
<meta name="msapplication-TileImage" content="/icons/icon-144x144.png" />
</head>
<body>{children}</body>
</html>
)
}
Icon generation script (run once)
bash
# Install sharp globally or as a dev dep
npm install -D sharp
# scripts/generate-icons.mjs
import sharp from 'sharp'
import { mkdirSync } from 'fs'
const sizes = [72, 96, 128, 144, 152, 180, 192, 384, 512]
mkdirSync('public/icons', { recursive: true })
for (const size of sizes) {
await sharp('public/icon-source.png')
.resize(size, size)
.png()
.toFile(`public/icons/icon-${size}x${size}.png`)
console.log(`Generated ${size}x${size}`)
}
// Maskable — add safe zone padding (10% each side)
await sharp('public/icon-source.png')
.resize(460, 460)
.extend({ top: 26, bottom: 26, left: 26, right: 26, background: '#1a1a2e' })
.resize(512, 512)
.png()
.toFile('public/icons/icon-maskable-512x512.png')
3. next-pwa Setup
Install
bash
npm install next-pwa
npm install -D @types/next-pwa # if using TypeScript
next.config.js
js
const withPWA = require('next-pwa')({
dest: 'public',
disable: process.env.NODE_ENV === 'development', // no SW in dev
register: true, // auto-register SW in _app or layout
skipWaiting: false, // we handle this manually for update prompt UX
reloadOnOnline: true, // reload page when network comes back
// Custom service worker file — optional but recommended for full control
// swSrc: 'src/sw.ts',
runtimeCaching: [
// Google Fonts — cache-first
{
urlPattern: /^https:\/\/fonts\.(?:googleapis|gstatic)\.com\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'google-fonts',
expiration: { maxEntries: 4, maxAgeSeconds: 365 * 24 * 60 * 60 },
},
},
// Static assets — cache-first
{
urlPattern: /\.(?:png|jpg|jpeg|svg|gif|webp|ico|woff2?)$/i,
handler: 'CacheFirst',
options: {
cacheName: 'static-assets',
expiration: { maxEntries: 64, maxAgeSeconds: 30 * 24 * 60 * 60 },
},
},
// Next.js static chunks — stale-while-revalidate
{
urlPattern: /^\/_next\/static\/.*/i,
handler: 'StaleWhileRevalidate',
options: { cacheName: 'next-static' },
},
// API routes — network-first with offline fallback
{
urlPattern: /^\/api\/.*/i,
handler: 'NetworkFirst',
options: {
cacheName: 'api-cache',
networkTimeoutSeconds: 10,
expiration: { maxEntries: 32, maxAgeSeconds: 24 * 60 * 60 },
},
},
// Pages — stale-while-revalidate
{
urlPattern: ({ request }) => request.destination === 'document',
handler: 'StaleWhileRevalidate',
options: {
cacheName: 'pages',
expiration: { maxEntries: 32 },
},
},
],
// Fallback to offline page when document fetch fails
fallbacks: {
document: '/offline',
},
buildExcludes: [/middleware-manifest\.json$/],
})
/** @type {import('next').NextConfig} */
const nextConfig = {
// your other next config
}
module.exports = withPWA(nextConfig)
.gitignore additions
# next-pwa generated files
public/sw.js
public/sw.js.map
public/workbox-*.js
public/workbox-*.js.map
public/fallback-*.js
public/fallback-*.js.map
4. Service Worker Patterns
Cache-First
Best for: fonts, images, icons, vendor JS — things that change rarely.
js
// Returns cached response immediately; fetches in background only if cache misses
{
handler: 'CacheFirst',
options: {
cacheName: 'static-v1',
expiration: {
maxEntries: 60,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 days
},
cacheableResponse: {
statuses: [0, 200], // 0 = opaque responses (cross-origin)
},
},
}
Network-First
Best for: API calls, authenticated data, anything that must be fresh.
js
// Tries network; falls back to cache on failure
{
handler: 'NetworkFirst',
options: {
cacheName: 'api-v1',
networkTimeoutSeconds: 10, // fall back to cache after 10s
expiration: {
maxEntries: 32,
maxAgeSeconds: 60 * 60, // 1 hour
},
},
}
Stale-While-Revalidate
Best for: pages, non-critical API data — serve instantly from cache, update silently.
js
{
handler: 'StaleWhileRevalidate',
options: {
cacheName: 'pages-v1',
expiration: {
maxEntries: 32,
maxAgeSeconds: 24 * 60 * 60, // 1 day
},
},
}
Custom service worker (public/sw-custom.js)
If you need logic beyond what next-pwa's config allows, use swSrc:
js
// public/sw-custom.js
// This file is merged with the Workbox-generated SW
import { precacheAndRoute } from 'workbox-precaching'
import { registerRoute } from 'workbox-routing'
import { CacheFirst, NetworkFirst, StaleWhileRevalidate } from 'workbox-strategies'
import { ExpirationPlugin } from 'workbox-expiration'
import { BackgroundSyncPlugin } from 'workbox-background-sync'
// Precache all assets from Next.js build
precacheAndRoute(self.__WB_MANIFEST || [])
// Custom route: user-specific data — never cache
registerRoute(
({ url }) => url.pathname.startsWith('/api/user/'),
new NetworkFirst({ networkTimeoutSeconds: 5 })
)
// Background sync for form submissions
const bgSyncPlugin = new BackgroundSyncPlugin('formQueue', {
maxRetentionTime: 24 * 60, // retry for 24 hours
})
registerRoute(
({ url }) => url.pathname.startsWith('/api/submit'),
new NetworkFirst({ plugins: [bgSyncPlugin] }),
'POST'
)
// Listen for skip-waiting message from update prompt
self.addEventListener('message', (event) => {
if (event.data?.type === 'SKIP_WAITING') {
self.skipWaiting()
}
})
5. Offline Fallback Page
app/offline/page.tsx
tsx
'use client'
import { useEffect, useState } from 'react'
export default function OfflinePage() {
const [isOnline, setIsOnline] = useState(false)
useEffect(() => {
setIsOnline(navigator.onLine)
const handleOnline = () => setIsOnline(true)
const handleOffline = () => setIsOnline(false)
window.addEventListener('online', handleOnline)
window.addEventListener('offline', handleOffline)
return () => {
window.removeEventListener('online', handleOnline)
window.removeEventListener('offline', handleOffline)
}
}, [])
const handleRetry = () => window.location.reload()
return (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minHeight: '100vh', gap: 16, padding: 24 }}>
<svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" aria-hidden="true">
<path d="M1 1l22 22M16.72 11.06A10.94 10.94 0 0 1 19 12.55M5 12.55a10.94 10.94 0 0 1 5.17-2.39M10.71 5.05A16 16 0 0 1 22.56 9M1.42 9a15.91 15.91 0 0 1 4.7-2.88M8.53 16.11a6 6 0 0 1 6.95 0M12 20h.01" strokeLinecap="round" strokeLinejoin="round" />
</svg>
<h1 style={{ fontSize: 24, fontWeight: 700, margin: 0 }}>You're offline</h1>
<p style={{ color: '#666', textAlign: 'center', maxWidth: 320, margin: 0 }}>
{isOnline
? 'Connection restored. You can retry now.'
: 'Check your internet connection and try again.'}
</p>
<button
onClick={handleRetry}
style={{ padding: '10px 24px', background: '#1a1a2e', color: '#fff', border: 'none', borderRadius: 8, cursor: 'pointer', fontSize: 16 }}
>
{isOnline ? 'Retry' : 'Try again'}
</button>
</div>
)
}
Online/offline hook for use anywhere in the app
tsx
// hooks/useNetworkStatus.ts
import { useEffect, useState } from 'react'
export function useNetworkStatus() {
const [isOnline, setIsOnline] = useState(true)
const [wasOffline, setWasOffline] = useState(false)
useEffect(() => {
setIsOnline(navigator.onLine)