Overview

MSW (Mock Service Worker) is an open-source library that provides API mocking by intercepting network requests at a low level in both browser and Node.js environments. Unlike many traditional mocking libraries that patch global objects like fetch or XMLHttpRequest, MSW utilizes Service Workers in the browser and a custom request interceptor in Node.js to achieve network-level interception. This approach allows developers to write mock handlers that operate on actual HTTP requests, simulating a real backend more accurately than in-memory mocks.

Developers primarily use MSW to decouple frontend development from backend availability. This enables frontend teams to build and test features even when the backend API is still under development or undergoing maintenance. For instance, a common use case involves defining mock API endpoints that return predefined data, allowing UI components to be developed and iterated upon without waiting for a functional server.

MSW is particularly well-suited for various testing scenarios. In end-to-end (E2E) testing, it allows tests to run against a consistent and controlled set of mock responses, eliminating external dependencies and improving test reliability and speed. For unit and integration tests, especially within frameworks like Jest or Vitest, MSW provides a realistic environment for testing components that interact with APIs. Furthermore, when developing components in isolation using tools like Storybook, MSW can be integrated to provide mock data, ensuring components render correctly with expected API responses.

The library supports both JavaScript and TypeScript, offering type safety for defining request handlers and response data. Its API is designed to be intuitive, allowing developers to define handlers for various HTTP methods (GET, POST, PUT, DELETE, etc.) and specify custom response statuses, headers, and body content. The flexibility to dynamic responses based on request parameters (e.g., URL, headers, body) enables complex mocking scenarios. MSW was founded in 2018 and has since gained adoption within the JavaScript ecosystem due to its network-level mocking capabilities and broad applicability across different development and testing workflows.

Key features

  • Network-level interception: Intercepts actual HTTP requests using Service Workers in browsers (supported by modern web browsers) and a dedicated module in Node.js, providing a more realistic mocking experience compared to in-memory mocks.
  • Environment agnostic: Works seamlessly in both browser environments for development and end-to-end testing, and in Node.js for unit and integration testing.
  • Declarative API: Offers a straightforward and expressive API for defining request handlers based on HTTP methods, paths, and patterns.
  • Dynamic responses: Allows developers to create dynamic mock responses, including custom status codes, headers, and body content, based on incoming request parameters.
  • GraphQL mocking: Supports mocking GraphQL queries and mutations by intercepting GraphQL requests and providing specific response data.
  • Integration with popular tools: Compatible with various JavaScript testing frameworks (e.g., Jest, Vitest, Cypress) and frontend development tools (e.g., Create React App, Next.js, Storybook).
  • Request matching: Enables flexible request matching using URL parameters, query parameters, headers, and request body content.
  • Persistent mocks: Once activated, mock handlers persist across page reloads (in the browser) or across test runs (in Node.js), ensuring consistent behavior.

Pricing

MSW is a fully open-source project and is available for free. There are no paid tiers or commercial versions.

Feature MSW (Open Source)
Cost Free
Browser Support Yes
Node.js Support Yes
GraphQL Mocking Yes
Community Support Yes

Pricing as of 2026-05-09. For the most current information, please refer to the MSW homepage.

Common integrations

  • React: Used for mocking API calls in React applications during development and testing. See MSW's React recipe.
  • Next.js: Integrates with Next.js for mocking data fetching during development and server-side rendering. See MSW's Next.js recipe.
  • Storybook: Provides mock data for isolated component development within Storybook. See MSW's Storybook recipe.
  • Jest: Commonly used with Jest for unit and integration testing of components that depend on APIs. See MSW's Jest recipe.
  • Cypress: Enables end-to-end testing with predictable API responses in Cypress tests. See MSW's Cypress recipe.
  • Playwright: Integrates with Playwright for reliable end-to-end testing with controlled network conditions. See MSW's Playwright recipe.

Alternatives

  • Mirage JS: An API mocking library that creates a mock server for your JavaScript application, often used for frontend development and testing.
  • JSON Server: A tool that allows you to create a full fake REST API with zero coding in less than 30 seconds.
  • Nock: An HTTP mocking and recording library for Node.js, primarily used for testing Node.js modules that make HTTP requests.

Getting started

To get started with MSW, you'll typically install it, create request handlers, and then integrate it into your development or test environment.

First, install MSW:

npm install msw --save-dev
# or
yarn add msw --dev

Next, define your request handlers. These handlers specify how MSW should respond to certain requests. For example, to mock a GET request to /user:

// src/mocks/handlers.ts
import { http, HttpResponse } from 'msw';

export const handlers = [
  http.get('https://example.com/user', () => {
    return HttpResponse.json({
      id: 'c3b5d2d0-1a7e-4b7c-8f0a-1e9a2b7c4d3e',
      firstName: 'John',
      lastName: 'Doe',
    }, { status: 200 });
  }),

  http.post('https://example.com/login', async ({ request }) => {
    const credentials = await request.json();
    if (credentials.username === 'user' && credentials.password === 'pass') {
      return HttpResponse.json({ success: true, token: 'fake-jwt-token' }, { status: 200 });
    }
    return HttpResponse.json({ success: false, message: 'Invalid credentials' }, { status: 401 });
  }),
];

To use MSW in a browser environment, you need to set up a Service Worker. MSW provides a CLI command for this:

npx msw init public/

Then, start the worker in your application's entry point (e.g., src/index.js or src/main.tsx):

// src/index.ts (for browser environments)
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

async function enableMocking() {
  if (process.env.NODE_ENV !== 'development') {
    return;
  }
  const { worker } = await import('./mocks/browser');
  return worker.start();
}

enableMocking().then(() => {
  ReactDOM.createRoot(document.getElementById('root')!).render(
    <React.StrictMode>
      <App />
    </React.StrictMode>,
  );
});

For Node.js environments (e.g., for testing), create a separate setup file:

// src/mocks/node.ts
import { setupServer } from 'msw/node';
import { handlers } from './handlers';

export const server = setupServer(...handlers);

And then use it in your test setup:

// jest.setup.ts or similar
import { server } from './src/mocks/node';

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

This setup allows your application to make real HTTP requests, which MSW will intercept and respond to with your defined mock data, providing a consistent and isolated development and testing experience.