Setup
If you have asrc/service-worker.js file (or src/service-worker/index.js), SvelteKit will bundle and automatically register it.
Service workers are bundled for production but not during development.
Automatic registration
The default registration looks like this:Custom registration
You can disable automatic registration and register manually:Inside the service worker
The$service-worker module provides access to:
string[]
Paths to all built app files
string[]
Paths to all files in the
static directorystring[]
Paths to all prerendered pages
string
A unique app version string for creating cache names
string
The deployment’s base path
Complete example
This example caches the built app and static files eagerly, then caches other requests as they happen:src/service-worker.js
1
Install event
Opens a cache and adds all static assets to it
2
Activate event
Removes old caches from previous deployments
3
Fetch event
Serves cached assets immediately, network resources with cache fallback
Caching strategies
Cache-first
Cache-first
Check the cache first, fall back to network. Best for static assets.
Network-first
Network-first
Try network first, fall back to cache if offline. Best for dynamic content.
Stale-while-revalidate
Stale-while-revalidate
Return cached response immediately while fetching fresh data in background.
Development considerations
During development:
- Service workers are not bundled
buildandprerenderedare empty arrays- Only browsers that support ES modules in service workers will work
Testing
1
Build your app
2
Preview the build
3
Test offline
Open DevTools → Network tab → Enable “Offline” mode
4
Verify caching
Open DevTools → Application tab → Service Workers / Cache Storage
Alternative solutions
SvelteKit’s service worker implementation is simple and effective, but you might prefer:Workbox
Google’s comprehensive PWA library with advanced caching strategies
Vite PWA Plugin
Workbox integration for Vite-based projects including SvelteKit
Learn more
MDN Web Docs: Using Service Workers