- Introduction
- Getting started
- Philosophy
- Comparison
- Limitations
- Debugging runbook
- FAQ
- Basics
- Concepts
- Network behavior
- Integrations
- API
- CLI
- Best practices
- Recipes
- Cookies
- Query parameters
- Response patching
- Polling
- Streaming
- Network errors
- File uploads
- Responding with binary
- Custom worker script location
- Global response delay
- GraphQL query batching
- Higher-order resolver
- Keeping mocks in sync
- Merging Service Workers
- Mock GraphQL schema
- Using CDN
- Using custom "homepage" property
- Using local HTTPS
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.
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)
Make sure to complete the Browser integration to
have the mockServiceWorker.js
script generated in your public directory and
thus available from the root of your application.
// 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)
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',
},
})