PWA with Serwist
This project uses Serwist for advanced PWA capabilities.
Features
- Build-time precache manifest: All static assets are precached during build
- Versioned cache names: Automatic cache versioning and cleanup
- Intelligent caching strategies:
- Pages: Stale-While-Revalidate
- Static assets (JS/CSS/fonts): Cache-First (7 days)
- Images: Cache-First with max 64 entries (30 days)
- API calls: Network-First with 10s timeout → cache fallback
- Offline fallback: Custom
/offlinepage when navigation fails - Background sync: Queue offline mutations and sync on reconnect
- Push notifications: Ready for push notification integration
Service Worker
The service worker is generated at build time from src/sw.ts using Serwist. In development mode, PWA features are disabled for faster iteration.
Custom Service Worker
Edit src/sw.ts to customize:
- Caching strategies
- Cache names and expiration
- Background sync logic
- Push notification handlers
Generated Files
During build, Serwist generates:
public/sw.js- The compiled service workerpublic/swe-worker-*.js- Additional worker scripts
These files are gitignored and regenerated on each build.
Development
Run pnpm dev - PWA is disabled, no service worker registration occurs.
Production
Run pnpm build && pnpm start - Service worker is registered and all PWA features are active.
Testing PWA
- Build the app:
pnpm build - Serve it:
pnpm start - Open Chrome DevTools → Application → Service Workers
- Check "Offline" to test offline functionality
- Navigate to any page - should fall back to
/offline - Test cache strategies in Network panel with throttling
Cache Strategies
| Resource | Strategy | Cache Duration | Max Entries |
|---|---|---|---|
| HTML Pages | Stale-While-Revalidate | 24 hours | 32 |
| Navigation | Network-First (3s timeout) | 24 hours | 32 |
| Static Assets | Cache-First | 7 days | 60 |
| Images | Cache-First | 30 days | 64 |
| Next.js Images | Cache-First | 30 days | 64 |
| API Routes | Network-First (10s timeout) | 5 minutes | 16 |
| Google Fonts | Stale-While-Revalidate | 30 days | 8 |
Offline Queue
The app uses IndexedDB to queue mutations when offline. See src/lib/offline/ for implementation details.
When connectivity returns:
- The
onlineevent triggers a flush - Background sync (if supported) triggers via service worker
- Queued operations replay in order
- Toast notifications confirm sync status
Updating the Service Worker
When you deploy a new version:
- Serwist automatically handles service worker updates
- Users get the new version on next page load
skipWaitingis enabled for immediate activation
Browser Support
- Chrome/Edge 90+
- Safari 14+ (limited background sync)
- Firefox 88+
- Requires HTTPS (or localhost for development)