- 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
Custom worker script location
Custom worker location
By default, calling worker.start()
will register the Service Worker script located at /mockServiceWorker.js
. You can customize the location of the worker script using the serviceWorker.url
option:
await worker.start({
serviceWorker: {
// This is useful if your application follows
// a strict directory structure.
url: '/assets/mockServiceWorker.js',
},
})
Changing the worker script’s location affects the scope at which the Service
Worker can intercept requests. For example, serving the worker script from a
/assets/
directory means that only the pages served under the /assets/
path and deeper can be affected by the worker (i.e. MSW).
Custom worker scope
There are multiple ways to allow the worker to control pages outside of its location. Note that all of these methods imply you have access to the development server, which with most modern frameworks you do to some extent. These suggestions may or may not work depending on the capabilities of the framework that you’re using.
Option 1: Proxy worker request
You can create a proxy from /mockServiceWorker.js
to any actual worker script location on the server. In that case, you can use the default worker.start()
call without the custom worker script location options.
Here’s an example of creating such a proxy request if your application is served by Express:
// This proxy request allows the browser to register the
// Service Worker from the root while proxying the worker
// script file from a nested location in "/assets/".
app.get('/mockServiceWorker.js', (req, res) => {
res.redirect('/assets/mockServiceWorker.js')
})
Please consult your framework’s setup to learn more about creating proxy routes.
Option 2: Service-Worker-Allowed
response header
You can tell the browser to ignore the default worker scope limitation by sending the Service-Worker-Allowed
header in the response to the requested worker script.
app.get('/assets/mockServiceWorker.js', (req, res, next) => {
// Allow the worker to control all the pages of the app.
res.setHeader('Service-Worker-Allowed', '/')
next()
})
The Service-Worker-Allowed
header must be present on the response to the worker script:
GET /assets/mockServiceWorker.js HTTP/1.0
content-type: application/javascript; charset=utf-8;
service-worker-allowed: /
<CONTENTS OF THE FILE>