juniorPWA

What are service workers in PWA, and what role do they play?

Updated Feb 20, 2026

Short answer

Service workers are background JavaScript files that act as a programmable network proxy between a PWA and the browser. They enable key PWA features such as offline support, caching, background synchronization, and push notifications. A service worker runs separately from the web page, allowing the application to provide a more reliable, app-like experience even with poor or no network connectivity.

Deep explanation

A service worker is a special type of web worker that the browser runs in the background. Unlike normal JavaScript running inside a webpage, a service worker does not have direct access to the DOM and does not run continuously. Instead, it is event-driven: the browser starts it when an event occurs, such as a network request, push notification, or background sync task.

The main role of a service worker in a Progressive Web App (PWA) is to control how the application interacts with the network.

A typical request flow looks like this:

TypeScript
User opens PWA
|
v
Browser requests a resource (HTML, CSS, API data, image)
|
v
Service Worker intercepts request
|
+----------------+
| |
v v
Return cached data Fetch from network

The service worker can decide whether to:

  • Serve a cached version of a resource.
  • Fetch the latest version from the server.
  • Return cached content immediately and update it in the background.
  • Provide a fallback response when the user is offline.

Service worker lifecycle

A service worker has three main lifecycle phases:

1. Registration

The web application registers the service worker with the browser.

JavaScript
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/service-worker.js")
.then(() => {
console.log("Service Worker registered");
});
}

The browser downloads and installs the service worker file.

2. Installation

During installation, developers usually cache important application resources.

JavaScript
const CACHE_NAME = "app-cache-v1";
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll([
"/",
"/index.html",
"/styles.css",
"/app.js"
]);
})
);
});

This allows the application shell to load even without an internet connection.

3. Activation

After installation, the service worker becomes active and can remove old caches or take control of pages.

JavaScript
self.addEventListener("activate", (event) => {
console.log("Service Worker activated");
});

Fetch event handling

The most important service worker capability is intercepting network requests.

JavaScript
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request)
.then((cachedResponse) => {
return cachedResponse || fetch(event.request);
})
);
});

In this example:

  • The service worker first checks whether the requested resource exists in the cache.
  • If it exists, it returns the cached response.
  • Otherwise, it requests the resource from the network.

Important PWA features enabled by service workers

Offline functionality

Service workers allow a PWA to continue working without an internet connection by serving cached resources.

Example:

  • A user opens a news PWA while online.
  • Articles are cached.
  • Later, the user opens the app on a flight.
  • Previously cached content can still be displayed.

Faster loading

Cached assets can be returned immediately instead of downloading them again, reducing load times.

Background synchronization

A service worker can retry failed operations when connectivity returns.

Example:

  • A user writes a message while offline.
  • The app stores it locally.
  • The service worker sends it automatically when the network becomes available.

Push notifications

Service workers can receive push events even when the webpage is not open.

Example:

  • A user receives a notification about a new message.
  • The service worker handles the push event and displays the notification.

Caching strategies

Different applications use different caching approaches:

StrategyDescriptionCommon Use
Cache FirstCheck cache before networkStatic assets
Network FirstTry network, fallback to cacheFrequently updated data
Stale While RevalidateReturn cache immediately and update in backgroundNews feeds, APIs
Network OnlyAlways use networkSensitive real-time data

Important limitations and considerations

Service workers improve reliability but introduce complexity:

  • Cached files can become outdated if cache versions are not managed correctly.
  • Service workers require HTTPS in production (except localhost during development).
  • Debugging can be harder because service workers run separately from the page.
  • A poorly designed caching strategy can show stale or incorrect data.

Real-world example

Consider an online shopping PWA. A user browses products while connected to Wi-Fi. The app caches product images, layout files, and previously viewed product information.

Later, the user loses connectivity while traveling. The service worker allows the app shell to load and displays cached products. When the connection returns, the service worker fetches updated product data.

Example service worker:

JavaScript
const CACHE = "shop-v1";
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE).then((cache) =>
cache.addAll([
"/",
"/products.html",
"/app.css",
"/app.js"
])
)
);
});
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request)
.then((response) => response || fetch(event.request))
);
});

This simple implementation provides a basic offline experience by using cached resources whenever possible.

Common mistakes

  • * Assuming a service worker is the same as a normal JavaScript file running inside the webpage.
  • * Forgetting that service workers cannot directly access or modify the DOM.
  • * Registering a service worker without planning a cache versioning strategy.
  • * Caching API responses forever and accidentally showing outdated data.
  • * Expecting service workers to work on insecure HTTP websites in production.
  • * Ignoring service worker lifecycle events such as installation and activation.
  • * Using a service worker for tasks that require continuous execution, since service workers can be stopped by the browser.
  • * Not testing update behavior when deploying a new version of the application.

Follow-up questions

  • What is the difference between a service worker and a web worker?
  • Why do service workers require HTTPS?
  • How does a service worker update itself?
  • What happens if a user is offline and opens a PWA for the first time?
  • What are common caching strategies used with service workers?
  • Can a service worker directly modify a webpage?

More PWA interview questions

View all →