12k
All articles

Writing Service Workers as ES Modules

Convert a service worker to an ES module with static imports, shared code, build options, update caching guidance, and a fallback for older browsers.

OpenReplay Team
OpenReplay Team
Writing Service Workers as ES Modules

To run a service worker as an ES module, call navigator.serviceWorker.register('/sw.js', { type: 'module' }). Without that option the browser loads the file as a classic script, so import and export are syntax errors.

Most teams arrive here the same way. The app is all ESM, built with Vite, and the service worker is still a classic script calling importScripts() on a hand-copied config file that drifts out of sync with the app. Switching the worker to a module fixes that, but module workers follow different rules, and browser support only became complete with Firefox 147. This article covers the registration change, sharing code with the page, the rules that break module workers, how updates behave, build output, and a fallback. For lifecycle basics, see A Practical Guide to Service Workers.

Key Takeaways

  • Passing { type: 'module' } to register() makes the service worker an ES module. The default type is 'classic'.
  • Calling importScripts() in a module worker throws a TypeError, so every call has to become a static import.
  • Dynamic import() and import maps don’t work in service workers, so every specifier must resolve to a real URL at build time.
  • Module service workers work in Chrome and Edge 91+, Safari 15+ and Firefox 147+.
  • The default updateViaCache: 'imports' setting lets update checks serve imported modules from the HTTP cache, so give shared modules hashed URLs or short cache lifetimes.

How Do You Switch a Service Worker to an ES Module?

Switching a service worker to an ES module takes two changes: pass the type option when you register, and swap importScripts() for import. In MDN’s register() reference, type takes 'classic' (the default) or 'module'.

Here is the classic version:

// config.js (classic)
self.CACHE_NAME = 'app-v3';

// sw.js (classic)
importScripts('/config.js');
console.log(self.CACHE_NAME);

And the module version:

// config.js (module)
export const CACHE_NAME = 'app-v3';

// sw.js (module)
import { CACHE_NAME } from './config.js';
console.log(CACHE_NAME);

Module scripts load with CORS, run in strict mode, and must be served with a JavaScript MIME type such as text/javascript, as the MDN Worker() constructor page explains for module workers.

Sharing Code Between the Page and the Worker

The main reason to write a service worker as an ES module is that one module can serve both the page and the worker. Put the cache name and the precache list in a single file:

// config.js
export const CACHE_NAME = 'app-v3';
export const PRECACHE_URLS = ['/', '/index.html', '/offline.html'];

The worker imports both values and uses standard Cache API calls:

// sw.js
import { CACHE_NAME, PRECACHE_URLS } from './config.js';

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => cache.addAll(PRECACHE_URLS))
  );
});

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((keys) =>
      Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)))
    )
  );
});

The page imports the same file:

// main.js, loaded via <script type="module">
import { CACHE_NAME } from './config.js';

console.debug('Expected cache:', CACHE_NAME);
navigator.serviceWorker.register('/sw.js', { type: 'module' });

Now you bump the version string in one place, and both sides see the change.

Three Rules That Break Module Service Workers

Three rules cause most failures when a classic service worker is converted to an ES module.

  1. No importScripts(). The HTML spec’s importScripts() steps throw a TypeError when the global scope’s type is "module", and MDN’s importScripts() reference points module workers to import instead. If your worker loads a library through importScripts(), you need an ESM build of that library.
  2. No dynamic import(). The MDN ServiceWorker page says the spec forbids dynamic import() in service workers and that calling it throws. Load any code you need conditionally up front with a static import.
  3. No import maps. Import maps don’t apply inside service workers, and support for them in workers is still an open proposal (whatwg/html #8173). Every specifier has to be a relative or absolute URL. A bare name such as 'idb' won’t resolve as a module specifier, so a build step must rewrite it or inline it.

How Imported Modules Affect Service Worker Updates

In a module service worker, imported modules are part of the update check. A change to a statically imported file such as config.js can start the update flow even when sw.js hasn’t changed, the same way importScripts() dependencies are handled, as Chrome’s announcement of module service workers notes.

The updateViaCache option decides whether those checks can use the HTTP cache:

ValueMain scriptImported modules
'imports' (default)Always from networkHTTP cache allowed
'all'HTTP cache allowedHTTP cache allowed
'none'Always from networkAlways from network

Under the default, a shared module served from a non-hashed URL with a long max-age can stay stale through update checks. You can serve shared modules from content-hashed URLs, give them short cache lifetimes, or register with updateViaCache: 'none'. Session replays of users still on old UI after a deploy, or of requests for hashed assets that no longer exist, often point to this kind of update bug. Debugging service workers covers how to confirm which worker version is in control.

Build Tools: Unbundled ESM or a Single File

Vite treats a service worker like any other output file: it has to be emitted as its own entry at a stable, unhashed URL such as /sw.js. If the URL changes on every build, the registration points at a different script each time. Vite’s public directory copies files without processing them, which suits a hand-written worker but doesn’t resolve its imports.

You can build a module service worker in one of two ways:

  • Unbundled ESM. sw.js and its shared modules ship as separate files with URL specifiers, and you register with type: 'module'. Each import is a separate fetch and is covered by the update check.
  • A single bundled file. The bundler inlines everything, including bare-specifier packages, into one script. If that output contains no import statements, it also runs as a classic worker, which makes it your fallback.

Fallback for Browsers Without Module Support

All four major engines support module service workers, according to MDN browser-compat-data on caniuse:

BrowserFirst version with type: 'module'
Chrome91
Edge91
Safari (macOS and iOS)15
Firefox147, per the Firefox 147 release notes

You only need a classic build for older browsers: Chrome and Edge 90 and earlier, Safari 14.1 and earlier, and Firefox 146 and earlier. No standard API detects module support, as the feature-detection request in w3c/ServiceWorker #1582 shows. An older browser doesn’t reject the type option up front. It downloads the script, fails to evaluate it, and register() rejects. You can catch that rejection:

async function registerSW() {
  if (!('serviceWorker' in navigator)) return;
  try {
    return await navigator.serviceWorker.register('/sw.js', { type: 'module' });
  } catch (err) {
    console.warn('Module service worker failed, falling back to classic:', err);
    return navigator.serviceWorker.register('/sw-classic.js');
  }
}

This try/catch fallback has two costs. Older browsers download the module script for nothing. And the catch also hides real errors in the module worker in supported browsers, so log the error before falling back.

Conclusion

Converting a service worker to a module comes down to the type option plus three rules: static imports only, no importScripts(), and no bare specifiers. To start, move the constants your worker and page duplicate into one shared module, register with { type: 'module' }, and check how that module is cached so a change to it reaches users through the update check.

FAQs

Can I use top-level await in a module service worker?

No. Top-level await is disallowed in service workers because the initial evaluation has to finish synchronously so that listeners such as install and fetch are attached in time. Chromium rejects the registration with a TypeError. This also applies when the await sits in a statically imported module, because it makes the whole module graph asynchronous. Move async setup into an install or activate handler wrapped in event.waitUntil().

Does switching an existing service worker from classic to module at the same URL trigger an update?

Yes. The Service Workers spec treats a change of worker type as an update, even when the script URL and its contents are identical. Calling register('/sw.js', { type: 'module' }) over an existing classic registration installs a new worker, which then goes through the normal waiting and activation lifecycle. A register() call with the same URL, type and updateViaCache value resolves without fetching anything.

Can a module service worker import modules from a CDN or another origin?

Yes, if the other origin allows it. Module imports are fetched with CORS, so a cross-origin module must be served with an Access-Control-Allow-Origin header that permits your origin. Otherwise the import fails and register() rejects. Classic importScripts() calls don't need this because they load scripts in no-cors mode. The service worker script itself must still be same-origin with the page that registers it.

Understand every bug

Uncover frustrations, understand bugs and fix slowdowns like never before with OpenReplay — self-hosted, with full data ownership.

Star on GitHub

We use cookies to improve your experience. By using our site, you accept cookies.