The Service Worker Scope
What you'll learn: How a service worker's scope defines exactly which pages it can control and intercept network requests for.
What Is Scope?
When you register a service worker, you define its scope — the range of URLs under your site's control that the service worker can manage. Think of scope like a security guard's patrol area: they can only monitor and control what happens within their assigned zone, not the entire building.
By default, a service worker's scope is determined by the folder where the service worker file lives. If your service worker is at /js/sw.js, its default scope is /js/ and everything beneath it. But here's the catch: most apps want to control the entire site from the root (/), so the service worker file typically lives at the root level: /sw.js.
Why Scope Matters
Scope determines which pages the service worker can:
- Intercept network requests for (fetch events)
- Receive navigation events from
- Control for caching and offline functionality
If your service worker is scoped to /app/, it cannot intercept requests from /blog/ or the homepage /. They're outside its jurisdiction.
Setting Scope Explicitly
When registering, you can explicitly set the scope:
navigator.serviceWorker.register('/sw.js', {
scope: '/app/'
});
However, you cannot set a scope broader than the service worker's location. A service worker at /js/sw.js cannot control / — that would be a security risk. The file must physically live at or above its intended scope.
Key Takeaway: A service worker's scope defines which pages it controls, defaulting to its file location's directory. Place your service worker file at the root level to control your entire site, or use explicit scoping for selective control.