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',
  },
})

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>