Skip to main content
Service workers act as proxy servers that handle network requests inside your app. This makes it possible to make your app work offline and speed up navigation by precaching built assets.

Setup

If you have a src/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:
During development, you must pass type: 'module' because only browsers that support modules in service workers can use them at dev time.

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 directory
string[]
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

Check the cache first, fall back to network. Best for static assets.
Try network first, fall back to cache if offline. Best for dynamic content.
Return cached response immediately while fetching fresh data in background.
Be careful when caching! In some cases, stale data might be worse than no data. Browsers will also empty caches if they get too full.

Development considerations

During development:
  • Service workers are not bundled
  • build and prerendered are 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