Skip to main content

What does a Service Worker do?

What a Service Worker is

A Service Worker is a special background script that the browser runs between the page and the network, and which can intercept network requests, cache responses, and react to events (fetch, push, sync) even when the tab is closed.

In simple terms, it's a "proxy server inside the browser".


How it works (architecturally)

javascript
┌──────────────┐ │ Internet │ └──────▲───────┘ │ │ (fetch request) ▼ ┌────────────────────┐ │ Service Worker │ ← a "proxy" between the page and the network │ ├ intercept fetch()│ │ ├ serve from cache │ │ ├ push notifications│ │ └ background sync │ └────────▲────────────┘ │ │ ┌────────────────────┐ │ Site tab │ └────────────────────┘

Service Worker lifecycle

  1. Registration The site tells the browser where the worker is:
javascript
navigator.serviceWorker.register('/sw.js');
  1. Install The worker is downloaded and installed (once).

  2. Activate Old versions are removed, the new worker becomes active.

  3. Running (fetch / push / sync) After activation, the worker listens for events:

  • fetch intercepts requests;
  • push handles notifications;
  • sync handles background tasks.
  1. Idle / terminate When not in use, the browser unloads it from memory, and starts it again on the next event.

Example: a basic Service Worker

sw.js

javascript
self.addEventListener('install', (event) => { console.log('Service Worker installing...'); event.waitUntil( caches.open('v1').then(cache => cache.addAll([ '/', '/index.html', '/styles.css', '/app.js' ])) ); }); self.addEventListener('activate', () => { console.log('Service Worker activated!'); }); self.addEventListener('fetch', (event) => { console.log('Request intercepted:', event.request.url); event.respondWith( caches.match(event.request).then(response => { return response || fetch(event.request); // from cache or from the network }) ); });

This SW:

  • saves files to the cache on install,
  • intercepts all requests,
  • serves from the cache if it exists,
  • otherwise goes to the network.

Example of registration in the main code

javascript
if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js') .then(() => console.log('SW registered')) .catch(console.error); }

Main Service Worker capabilities

CapabilityWhat it does
Fetch interceptionIntercepts and controls all network requests
Caching APIStores files and responses in a cache (offline support)
Background syncRuns tasks once the network is back
Push notificationsReceives push notifications from the server
Offline-firstLets the site work without internet
Periodic syncRuns actions on a schedule
Proxy layerImproves security (controls requests and responses)

Example of an offline page

javascript
self.addEventListener('fetch', (event) => { event.respondWith( fetch(event.request).catch(() => caches.match('/offline.html')) ); });

If there is no internet, it returns /offline.html so the site doesn't break, it shows "You are offline".


Push notifications

javascript
self.addEventListener('push', (event) => { const data = event.data.json(); event.waitUntil( self.registration.showNotification(data.title, { body: data.body, icon: '/icon.png' }) ); });

Works even when the tab is closed, the browser "wakes" the Service Worker to handle push.


Background Sync

Lets you run deferred tasks once the network is back:

javascript
self.addEventListener('sync', (event) => { if (event.tag === 'sendFormData') { event.waitUntil(sendDataToServer()); } });

For example, the user is offline, data is saved to IndexedDB, and once the network is back, the Service Worker sends it to the server itself.


Limitations

FeatureDescription
Isolated from the DOMNo window, document
HTTPS onlyWorks only on secure domains (or localhost)
Limited memory accessThere are cache quotas
Unloaded automatically"Wakes up" on events, does not run continuously

Where it's actually used

  • PWA (Progressive Web Apps)
  • offline access, "Add to Home Screen", instant loading
  • News / chat apps
  • push notifications without an open tab
  • Games / offline modes
  • loading assets and data into the cache
  • Web services
  • caching API responses, saving traffic

A simple analogy

Imagine the Service Worker as the site's guard

  • it stands "at the door" between the page and the internet,
  • it decides: "serve from the cache or go to the network",
  • it can show notifications,
  • it keeps working even when the shop (the tab) is closed.

Summary

ParameterDescription
TypeA background JS process between the page and the network
Main functionsIntercepting requests, cache, push, background sync
Works with the tab closedYes
DOM accessNone
Requires HTTPSYes
Main usePWA, offline mode, notifications

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.