Back to docsRecipe

MSW setup primer

Mock Service Worker intercepts network requests at the service-worker level so your tests and local dev hit realistic handlers instead of live APIs. No stubbed fetch, no monkey-patched axios — just standard Request/Response objects flowing through the same code paths your users hit.

Why MSW over mocks

  • Network-level interception — works with fetch, axios, ky, graphql-request
  • Same handlers power Jest, Vitest, Playwright, and Storybook
  • No production bundle bloat — handlers live in dev/test trees

Quick start

1. Install

npm i -D msw@latest

2. Define handlers

import { http, HttpResponse } from 'msw'

export const handlers = [
  http.get('/api/user', () =>
    HttpResponse.json({ id: 1, name: 'Ada' })
  ),
]

3. Register in tests

import { setupServer } from 'msw/node'
import { handlers } from './handlers'

const server = setupServer(...handlers)
beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())

Pro tip: Keep handlers colocated with the feature they mock. When the API contract changes, the handler and the consuming component break together — no stale mocks surviving in a shared utils folder.