# How to intercept fetch calls in browser tests with MSW

> Share MSW handlers between Chromium and Node tests, assert what a component renders for a 500, and fail unhandled requests with the MSW 3 option onUnhandledFrame.

Source: https://voxgig.com/howto/intercept-fetch-in-browser-tests-with-msw

- Audience: api-consumer
- Level: intermediate
- Languages: typescript, javascript
- Verified: 2026-11-30
- Published: 2026-11-30

## Short answer

Write MSW request handlers once, start them with `setupWorker` in the browser and `setupServer` in Node, and override one per test with `use()` to return a 500. The component's own fetch code runs against them with no server. In MSW 3, pass `onUnhandledFrame: 'error'`, because MSW 3 ignores the MSW 2 name `onUnhandledRequest`, keeps its default of a warning, and lets unmatched requests reach the network.

---
## You will need

Node 22.12 or later, because msw 3.0.8 declares `>=22.12.0` in its `engines` field. A browser
runner for the browser half: the sample drives Chromium through Playwright. TypeScript is optional
and catches the renamed option. Verified 2026-11-30 against Node 22.23.5, msw 3.0.8, TypeScript
5.9.3, Playwright 1.63.0 and Chromium `158.0.8127.36`.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Cypress cy.intercept](https://docs.cypress.io/api/commands/intercept) | The suite already runs in Cypress and one spec needs one stub | Stubs live inside Cypress specs, so Node unit tests cannot reuse them | Unit tests and browser tests need the same responses |
| [MSW](https://mswjs.io/docs/http/intercepting-requests) | Unit, component and end to end tests should share one set of responses | A dependency, a worker script served from your origin, and an option renamed between majors | One spec needs one stub inside a runner that already intercepts |
| [Playwright page.route](https://playwright.dev/docs/mock) | The suite already runs in Playwright and a stub serves one spec | Routes exist only in Playwright, and unmatched requests reach the network without a catch-all | The same handlers must serve a Node suite too |

MSW intercepts inside the page through a service worker, so the component's own `fetch` runs and
the handlers move to Node unchanged. Its price is setup: a worker file on your origin and a
start-up call before the first request. `page.route` and `cy.intercept` need neither, and a
one-off stub is a single call. Their stubs belong to one runner, so a `node --test` or Vitest suite
cannot load them.

## Write the handlers once

A handler pairs a method and a URL pattern with a response. The `*` origin matches the page's own
origin in a browser and any base URL a Node test passes.

```js title="handlers.js"
import { http, HttpResponse } from 'msw'

// One set of handlers for every runner. The wildcard origin matches the page's
// own origin in a browser and any base URL a Node test passes.
export const handlers = [
  http.get('*/api/user', () => HttpResponse.json({ name: 'Ada Lovelace', plan: 'Team' })),
]

// Per-test overrides, applied with worker.use() or server.use().
export const userFails = http.get('*/api/user', () =>
  HttpResponse.json({ error: 'upstream unavailable' }, { status: 500 }),
)
```

The component, `profile.js`, fetches `api/user` relative to a base URL and returns an alert for
any status that is not 2xx. It knows nothing about MSW, which is the point: the code under test is
the code that ships.

## Start the worker in the page

In the browser, `setupWorker` registers `mockServiceWorker.js`, which answers the page's requests
from the handlers. The MSW documentation has you copy that file into your public directory with
[`npx msw init`](https://mswjs.io/guides/integrations/browser), so it is served from your
origin.[^1]

```js title="browser/msw-run.js"
import { setupWorker } from 'msw/browser'
import { handlers, userFails } from '../handlers.js'
import { mountProfile } from '../profile.js'

const worker = setupWorker(...handlers)
await worker.start({
  serviceWorker: { url: '/mockServiceWorker.js' },
  onUnhandledFrame: 'error',
  quiet: true,
})

const root = /** @type {HTMLElement} */ (document.querySelector('#profile'))
const base = `${location.origin}/`
const results = {}
results.shared = await mountProfile(root, base)
worker.use(userFails)
results.fails = await mountProfile(root, base)
```

`worker.use(userFails)` puts the 500 in front of the shared handler, and `worker.resetHandlers()`
takes it away again. The sample has no bundler, so `browser/index.html` loads MSW's IIFE build and
an import map points `msw` at it. With Vite or Vitest browser mode, that shim goes away.

The gate that checks this page has no browser, so `record.sh` runs the page once in Chromium.
Its static server has no `/api/` routes and counts every request that reaches one.

```bash
cat records/browser-run.txt
```

```text output
Chromium 158.0.8127.36, Playwright 1.63.0, msw 3.0.8
MSW setupWorker with the shared handlers
  shared handler, text shown: "Ada LovelaceTeam plan"
  then worker.use(userFails):
  /api/user, text shown:      "Profile unavailable: HTTP 500"
  markup on the page at exit: <p role="alert">Profile unavailable: HTTP 500</p>
  unhandled GET /api/billing: answered 500, body.message: [MSW] Cannot bypass a request when using the "error" strategy for the "onUnhandledFrame" option.
  console: [MSW] Error: intercepted a request without a matching request handler:
  requests that reached the static server: none
```

The page rendered both states without a single request reaching the server.

## Run the same handlers in Node

`setupServer` takes the same handler array and intercepts `fetch`, `http` and `XMLHttpRequest`
calls in the process.[^2] The setup file sets the unhandled-request strategy, and its self-check
refuses to run the suite when MSW cannot see the requests at all.

```js title="mocks.js"
import { setupServer } from 'msw/node'
import { http, HttpResponse } from 'msw'
import { handlers } from './handlers.js'

export const server = setupServer(...handlers)

// MSW 3 reads onUnhandledFrame. MSW 2 called it onUnhandledRequest, and MSW 3
// ignores that name without a word, falling back to "warn".
// The self-check sends one request to the API's own host and refuses to go on
// unless MSW answered it, which it does not when Node sends fetch to a proxy.
/** @param {string | URL} apiBase */
export async function startMocking(apiBase) {
  server.listen({ onUnhandledFrame: 'error' })
  const probe = new URL('/__msw-self-check', apiBase)
  const token = crypto.randomUUID()
  server.use(http.get(probe.href, () => HttpResponse.text(token)))
  const answer = await fetch(probe, { signal: AbortSignal.timeout(5_000) }).then(
    (res) => res.text(),
    () => null,
  )
  server.resetHandlers()
  if (answer !== token) {
    server.close()
    throw new Error(
      `MSW did not answer a request to ${probe.origin}. If NODE_USE_ENV_PROXY or ` +
        '--use-env-proxy is on, add that host to NO_PROXY for the test run.',
    )
  }
}
```

The tests point the component at `http://api.example.test/v1/`, a host with no server behind it.
Each override is reset after its test, so one test's 500 never leaks into the next.

```js title="profile.test.mjs"
test.before(() => startMocking(API))
test.afterEach(() => server.resetHandlers())
test.after(() => server.close())

test('renders the user from the shared handler', async () => {
  assert.equal(await profileView(API), '<h2>Ada Lovelace</h2><p>Team plan</p>')
})

test('renders an alert when the API answers 500', async () => {
  server.use(userFails)
  assert.equal(await profileView(API), '<p role="alert">Profile unavailable: HTTP 500</p>')
})
```

## Keep a proxy from bypassing the handlers

A suite that passed locally fails on a runner that sets `NODE_USE_ENV_PROXY=1`. Node 22 then tunnels
requests over the proxy that `HTTP_PROXY` or `HTTPS_PROXY` names, as the
[`NODE_USE_ENV_PROXY` reference](https://nodejs.org/docs/latest-v22.x/api/cli.html#node_use_env_proxy1)
describes. `proxy.mjs` requests a URL the shared handler covers, with a stand-in proxy on
127.0.0.1 that counts what reaches it.

```bash
node proxy.mjs
```

```text output
GET http://api.example.test/v1/api/user, a URL the shared handler covers
no proxy settings
  MSW printed: nothing
  request:     answered 200 {"name":"Ada Lovelace","plan":"Team"}
  reached the stand-in proxy: 0
NODE_USE_ENV_PROXY=1 and HTTP_PROXY
  MSW printed: nothing
  request:     rejected by fetch
  reached the stand-in proxy: 1
the same, plus NO_PROXY=api.example.test
  MSW printed: nothing
  request:     answered 200 {"name":"Ada Lovelace","plan":"Team"}
  reached the stand-in proxy: 0
NODE_USE_ENV_PROXY=1 and HTTP_PROXY, through startMocking()
  MSW printed: nothing
  request:     rejected: MSW did not answer a request to http://api.example.test. If NODE_USE_ENV_PROXY or --use-env-proxy is on, add that host to NO_PROXY for the test run.
  reached the stand-in proxy: 1
```

With the proxy on, msw 3.0.8 neither answered from its handler nor reported the request as
unhandled, so `onUnhandledFrame: 'error'` never fired. The call went to the proxy, which is the
network path the strategy exists to close. Listing the API host in `NO_PROXY` restores interception, and the self-check in
`startMocking` turns the silent case into a failed start.

## Check it worked

Run the Node suite:

```bash
node --test profile.test.mjs
```

```text output
1..8
# tests 8
# suites 0
# pass 8
# fail 0
# cancelled 0
# skipped 0
# todo 0
```

Eight tests pass. The 500 test expects the literal `<p role="alert">Profile unavailable: HTTP 500</p>`,
the same markup the Chromium record shows. The last test reads `records/browser-run.txt` and fails
if the committed browser run stops showing both renders or shows a request reaching the server.

## When it goes wrong

The suite passes at your desk and fails on a CI runner with no outbound access.
A request no handler covers went to the network. `unhandled.mjs` sends one such request to a
stand-in API on 127.0.0.1 under each `listen()` option and counts what arrives.

```bash
node unhandled.mjs
```

```text output
no MSW at all (control)
  MSW printed: nothing
  request:     answered 200 {"source":"network"}
  reached the stand-in API: 1
listen()
  MSW printed: warning
  request:     answered 200 {"source":"network"}
  reached the stand-in API: 1
listen({ onUnhandledRequest: 'error' })
  MSW printed: warning
  request:     answered 200 {"source":"network"}
  reached the stand-in API: 1
listen({ onUnhandledFrame: 'error' })
  MSW printed: error
  request:     rejected: [MSW] Cannot bypass a request when using the "error" strategy for the "onUnhandledFrame" option.
  reached the stand-in API: 0
```

The default is `warn`, which prints and lets the request through. The third case is the one that
costs an afternoon. The [2.x to 3.x migration guide](https://mswjs.io/docs/migrations/2.x-to-3.x)
lists the MSW 2 option name as renamed, and MSW 3 accepts it without an error and keeps `warn`. Use
[`onUnhandledFrame`](https://mswjs.io/api/setup-server/listen), and type-check the setup file so
the MSW 2 name fails the build:

```bash
npx tsc -p pitfall
```

```text output
pitfall/mocks-v2.js(8,19): error TS2353: Object literal may only specify known properties, and 'onUnhandledRequest' does not exist in type 'PartialObjectDeep<SharedOptions, { recurseIntoArrays: false; allowUndefinedInNonTupleArrays: false; }>'.
```

The sample's `tsconfig.json` sets `checkJs`, so plain JavaScript setup files get the same check.

In Chromium the same strategy does not reject the call. The worker answered the unhandled
`GET /api/billing` with a 500 carrying MSW's message, as the record shows. A component that shows
an alert for any 500 shows one here too, so a typo in a handler's URL can pass a test that expects
the alert. `record.mjs` collects the page's console for that reason, and the `[MSW] Error` line is
the visible sign of the miss.

Every Node test fails with `MSW did not answer a request to http://api.example.test`. Node is
sending `fetch` to the proxy that `NODE_USE_ENV_PROXY` and `HTTP_PROXY` name, so `startMocking`
refuses to start, as the last case of `node proxy.mjs` shows. Add the API host to `NO_PROXY` for
the test run.

## When not to do this

Do not add MSW for one stub in one Playwright spec. `page.route` does it in the runner you already
have, with no worker file to serve and no start-up call to wait for. The browser record shows its
cost: the unmatched `GET /api/billing` reached the server until a catch-all `route.abort()` was
registered before the specific route.[^3]

```js title="record.mjs"
  await run('Playwright page.route, catch-all abort registered first', '/browser/route.html', async (page) => {
    await page.route('**/api/**', (route) => route.abort())
    await page.route('**/api/user', (route) =>
      route.fulfill({ status: 500, json: { error: 'upstream unavailable' } }),
    )
  })
```

Do not read a green run as proof that the API behaves this way. The handlers return what you
wrote, so a renamed field in the real response passes every test here. A contract test against
the provider is the check for that.

Do not leave the strategy at its default in CI. A warning in a log nobody reads is how a suite
comes to depend on the network.

## Related how-tos

- [Stub outbound HTTP calls in Node tests with nock](/howto/stub-outbound-node-http-calls-with-nock)

- [Choose between a network mock and an in-process mock](/howto/choose-between-network-and-in-process-mocks)

- [Run a local mock API for frontend development with Mockoon](/howto/run-a-local-mock-api-for-frontend-work)

- [Control which stub wins when mock rules overlap](/howto/control-which-stub-wins-when-rules-overlap)

- [Stub HTTP dependencies in Java tests with WireMock](/howto/stub-http-dependencies-in-java-tests)

## Last verified

Verified 2026-11-30 against Node 22.23.5, msw 3.0.8 and TypeScript 5.9.3, and in Chromium
`158.0.8127.36` through Playwright 1.63.0. Every output block is what the command before it printed.
The browser run happens once in `record.sh`, which commits its output. Cypress was not run, and
what this page says of `cy.intercept` comes from its documentation.

[^1]: Service workers run only in secure contexts, which the
[Service Workers specification](https://www.w3.org/TR/service-workers/#secure-context) takes to
mean HTTPS, with an allowance for development. The
[Secure Contexts](https://www.w3.org/TR/secure-contexts/#is-origin-trustworthy) algorithm counts
any host in 127.0.0.0/8 as potentially trustworthy, so the record's plain HTTP server on 127.0.0.1
qualifies by its address alone.

[^2]: The library's name describes its browser half. In Node no service worker is involved, and
the [`listen()` reference](https://mswjs.io/api/setup-server/listen) explains that the call is
synchronous because there are no workers to register. The installed 3.0.8 build lists four
interceptors for `setupServer`, one each for `ClientRequest`, `XMLHttpRequest`, `fetch` and
WebSocket.

[^3]: When routes overlap, the
[`page.route` reference](https://playwright.dev/docs/api/class-page) gives precedence to the route
registered last, so a catch-all goes in first to be consulted last. The same page gives HAR replay the opposite default:
`routeFromHAR` aborts a request the file does not hold unless `notFound` is set to `fallback`.