start()

Register the Service Worker and starts the request interception.

Call signature

The worker.start() method accepts an optional Options object that you can use to customize the worker registration.

By default, when called without any arguments, the worker.start() method registers the Service Worker served under ./mockServiceWorker.js and starts the request interception.

import { setupWorker } from 'msw/browser'
import { handlers } from './handlers'
 
const worker = setupWorker(...handlers)
await worker.start() // Promise<{ pending }>

You can see a confirmation message printed in the browser’s console when MSW is active.

[MSW] Mocking enabled.

Options

serviceWorker

url

  • String, default: "/mockServiceWorker.js"

Custom Service Worker registration URL. Use this option if you are serving the worker script under a custom path.

worker.start({
  serviceWorker: {
    url: '/assets/mockServiceWorker.js',
  },
})

options

These options modify the Service Worker registration itself and are not related to MSW directly.

worker.start({
  serviceWorker: {
    options: {
      // Narrow down the scope of the pages that the worker can control.
      scope: '/product',
    },
  },
})

findWorker

  • Function, expected return type: Boolean

A custom function to locate the worker script on the server. You may want to use this option if your application runs behind a proxy or has a dynamic hostname that otherwise prevents the library from locating the worker script at <HOSTNAME>/mockServiceWorker.js.

worker.start({
  findWorker(scriptUrl, mockServiceWorkerUrl) {
    return scriptUrl.includes('mockServiceWorker')
  },
})

quiet

  • Boolean, default: false

Disables all the logging from the library (e.g. the activation message, the intercepted requests’ messages).

worker.start({
  quiet: true,
})

onUnhandledRequest

  • String, default: "warn"
  • Function

Decide how to react to unhandled requests (i.e. those that do not have a matching request handler).

Standard modes

Handling modeDescription
warn (Default)Prints a warning message to the browser’s console, performs the request as-is.
errorThrows an error, aborts the request.
bypassPrints nothing, performs the request as-is.

Custom onUnhandledRequest function

worker.start({
  onUnhandledRequest(request, print) {
    // Ignore any requests containing "cdn.com" in their URL.
    if (request.url.includes('cdn.com')) {
      return
    }
 
    // Otherwise, print an unhandled request warning.
    print.warning()
  },
})

waitUntilReady

  • Boolean, default: true

Defers any application requests that happen during the Service Worker registration.