This file documents the service worker implementation used by the site.
- Service worker file:
public/sw.js - Registration client:
src/components/ServiceWorkerRegister.tsx - Root layout also renders
ServiceWorkerRegisterinsrc/app/layout.tsx.
- The service worker precaches a small set of core assets (
/,/manifest.webmanifest,/icon/favicon.ico). - Navigation requests (HTML) use a network-first strategy with a cache fallback.
- Static assets use a cache-first with background stale-while-revalidate update flow.
- The worker skips cross-origin requests, Next.js dev paths (
/_next/) and API calls.
The app registers the SW from two locations:
ServiceWorkerRegister component (src/components/ServiceWorkerRegister.tsx):
import { useEffect } from 'react';
export default function ServiceWorkerRegister() {
useEffect(() => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/sw.js')
.then((reg) => console.log('Service Worker registered with scope', reg.scope))
.catch((err) => console.error('Service Worker registration failed:', err));
}
}, []);
return null;
}Home page (src/app/page.tsx) also registers the SW within its useEffect as a defensive measure for client-side navigations.
Both registration points use identical registration logic to ensure the service worker is registered regardless of entry point.
Implementation: ServiceWorkerRegister.tsx, page.tsx
Edit public/sw.js to change PRECACHE_URLS, cache names, or strategy. Keep the SW path at /sw.js to match the registration call.