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 /offline page 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 worker
  • public/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

  1. Build the app: pnpm build
  2. Serve it: pnpm start
  3. Open Chrome DevTools → Application → Service Workers
  4. Check "Offline" to test offline functionality
  5. Navigate to any page - should fall back to /offline
  6. Test cache strategies in Network panel with throttling

Cache Strategies

ResourceStrategyCache DurationMax Entries
HTML PagesStale-While-Revalidate24 hours32
NavigationNetwork-First (3s timeout)24 hours32
Static AssetsCache-First7 days60
ImagesCache-First30 days64
Next.js ImagesCache-First30 days64
API RoutesNetwork-First (10s timeout)5 minutes16
Google FontsStale-While-Revalidate30 days8

Offline Queue

The app uses IndexedDB to queue mutations when offline. See src/lib/offline/ for implementation details.

When connectivity returns:

  1. The online event triggers a flush
  2. Background sync (if supported) triggers via service worker
  3. Queued operations replay in order
  4. Toast notifications confirm sync status

Updating the Service Worker

When you deploy a new version:

  1. Serwist automatically handles service worker updates
  2. Users get the new version on next page load
  3. skipWaiting is enabled for immediate activation

Browser Support

  • Chrome/Edge 90+
  • Safari 14+ (limited background sync)
  • Firefox 88+
  • Requires HTTPS (or localhost for development)

Learn More