Lesson 5 of 10
Service Workers & PWA
Service Workers are JavaScript workers that sit between your app and the network, enabling offline functionality, background sync, push notifications, and installable PWAs. In Next.js, next-pwa or Workbox handles the Service Worker lifecycle.
Service Workers - Core Concepts
// ---- Service Worker lifecycle ----
// install → activate → fetch (intercept requests)
// public/sw.js - plain Service Worker
const CACHE_NAME = 'app-v1';
const STATIC_ASSETS = ['/', '/about', '/offline.html', '/styles/main.css'];
// Install - cache static assets
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(STATIC_ASSETS))
);
self.skipWaiting(); // activate immediately
});
// Activate - clean up old caches
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then(names =>
Promise.all(names.filter(n => n !== CACHE_NAME).map(n => caches.delete(n)))
)
);
self.clients.claim(); // take control of all pages immediately
});
// Fetch - cache strategies
self.addEventListener('fetch', (event) => {
const { request } = event;
const url = new URL(request.url);
// Strategy 1: Cache First (images, fonts, static assets)
if (request.destination === 'image' || url.pathname.startsWith('/fonts/')) {
event.respondWith(
caches.match(request).then(cached => cached ?? fetch(request).then(response => {
const clone = response.clone();
caches.open(CACHE_NAME).then(cache => cache.put(request, clone));
return response;
}))
);
return;
}
// Strategy 2: Network First (API calls)
if (url.pathname.startsWith('/api/')) {
event.respondWith(
fetch(request).catch(() =>
caches.match(request) ?? // fallback to cached API response
Response.json({ error: 'Offline', offline: true }, { status: 503 })
)
);
return;
}
// Strategy 3: Stale While Revalidate (pages)
event.respondWith(
caches.open(CACHE_NAME).then(async cache => {
const cached = await cache.match(request);
const fetchPromise = fetch(request).then(response => {
cache.put(request, response.clone());
return response;
});
// Return cached immediately, update in background
return cached ?? fetchPromise;
})
);
});next-pwa - Next.js PWA Integration
// npm install next-pwa
// next.config.ts
import withPWA from 'next-pwa';
const nextConfig = withPWA({
dest: 'public', // generates public/sw.js and public/workbox-*.js
register: true, // auto-registers the service worker
skipWaiting: true,
disable: process.env.NODE_ENV === 'development', // disable in dev
runtimeCaching: [
{
urlPattern: /^https:\/\/api\.example\.com\/products/,
handler: 'StaleWhileRevalidate',
options: {
cacheName: 'products-api',
expiration: { maxEntries: 100, maxAgeSeconds: 3600 },
},
},
{
urlPattern: /\.(?:jpg|jpeg|png|webp|svg|gif|ico)$/,
handler: 'CacheFirst',
options: {
cacheName: 'images',
expiration: { maxEntries: 200, maxAgeSeconds: 30 * 24 * 3600 },
},
},
],
})({
reactStrictMode: true,
});
export default nextConfig;
// public/manifest.json - PWA installation config
{
"name": "My Awesome App",
"short_name": "MyApp",
"description": "A production React PWA",
"start_url": "/?source=pwa",
"display": "standalone", // no browser chrome when installed
"background_color": "#0f172a",
"theme_color": "#229c6b",
"orientation": "portrait-primary",
"icons": [
{ "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png" },
{ "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
],
"shortcuts": [
{ "name": "Dashboard", "url": "/dashboard", "icons": [{ "src": "/icons/dashboard.png", "sizes": "96x96" }] }
]
}
// Install prompt management
'use client';
import { useEffect, useState } from 'react';
interface BeforeInstallPromptEvent extends Event {
prompt(): Promise<void>;
userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>;
}
function useInstallPrompt() {
const [prompt, setPrompt] = useState<BeforeInstallPromptEvent | null>(null);
const [isInstalled, setIsInstalled] = useState(false);
useEffect(() => {
const handler = (e: Event) => {
e.preventDefault();
setPrompt(e as BeforeInstallPromptEvent);
};
window.addEventListener('beforeinstallprompt', handler);
window.addEventListener('appinstalled', () => setIsInstalled(true));
return () => window.removeEventListener('beforeinstallprompt', handler);
}, []);
async function install() {
if (!prompt) return;
await prompt.prompt();
const { outcome } = await prompt.userChoice;
if (outcome === 'accepted') setIsInstalled(true);
setPrompt(null);
}
return { canInstall: !!prompt && !isInstalled, install, isInstalled };
}
function InstallButton() {
const { canInstall, install } = useInstallPrompt();
if (!canInstall) return null;
return (
<button onClick={install} style={{ background: '#229c6b', color: 'white', padding: '8px 16px', borderRadius: 8, border: 'none', cursor: 'pointer' }}>
📱 Install App
</button>
);
}Push Notifications with Service Workers
// Subscribe user to push notifications
async function subscribeToPush() {
const registration = await navigator.serviceWorker.ready;
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true, // required - all pushes must show a notification
applicationServerKey: urlBase64ToUint8Array(process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY!),
});
// Send subscription to your server
await fetch('/api/push/subscribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(subscription),
});
}
// Service worker - handle push events
self.addEventListener('push', (event) => {
const data = event.data?.json() ?? {};
event.waitUntil(
self.registration.showNotification(data.title ?? 'New notification', {
body: data.body,
icon: '/icons/icon-192.png',
badge: '/icons/badge.png',
data: { url: data.url ?? '/' },
actions: [
{ action: 'open', title: 'Open App' },
{ action: 'dismiss', title: 'Dismiss' },
],
})
);
});
// Handle notification click
self.addEventListener('notificationclick', (event) => {
event.notification.close();
if (event.action === 'dismiss') return;
event.waitUntil(
clients.openWindow(event.notification.data.url)
);
});Tip
Tip
Practice Service Workers PWA in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for Service Workers & PWA
Practice Task
Note
Practice Task - (1) Write a working example of Service Workers PWA from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Service Workers PWA is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Finished this lesson?