Merging Service Workers

Use MSW with an existing Service Worker.

The browser can only register a single Service Worker per scope. This means that if your application already registers a Service Worker, it cannot register another one for MSW in parallel. You can still use both your custom Service Worker and MSW by merging the two worker scripts.

Import MSW’s worker in your existing worker

First, modify your existing worker script to conditionally import /mockServiceWorker.js. Use the importScripts() API available globally in the worker’s scope.

// public/existing-worker.js
const url = new URL(location.href)
 
if (url.searchParams.get('enableApiMocking') === 'true') {
  importScripts('/mockServiceWorker.js')
}
 
// The rest of your Service Worker script here.
// self.addEventListener('fetch', listener)
Enable API mocking conditionally
// src/app.js
const workerUrl = new URL('/existing-worker.js', location.origin)
 
// In your application code, set the "enableApiMocking" search parameter
// on the worker script URL. This way the client lets the worker know
// whether it should import MSW's worker script based on the environment.
if (process.env.NODE_ENV === 'development') {
  workerUrl.searchParams.set('enableApiMocking', 'true')
}
 
navigator.serviceWorker.register(workerUrl.href)
Set up MSW to use your worker

Lastly, provide your worker script URL as the serviceWorker.url option on the worker.start() call. Since the only Service Worker you register is your custom worker, let MSW know that it should use it to control the network.

worker.start({
  serviceWorker: {
    url: '/existing-worker.js',
  },
})