Seamless REST/GraphQL API mocking library for browser and Node.js.
Mock Service Worker (MSW) is a network-level API mocking library that intercepts HTTP requests using Service Workers in browsers and a custom interception algorithm in Node.js. Unlike traditional mocking libraries that stub fetch or axios directly, MSW operates after requests leave your application code, allowing your entire codebase to execute as it would in production while controlling network responses.
The library uses an Express-like API to define request handlers that capture matching requests and return mock responses. These handlers support REST endpoints, GraphQL operations, and other protocols, with full control over status codes, headers, cookies, and response delays. Because MSW intercepts at the network boundary rather than replacing client libraries, you can use the same mock definitions across unit tests, integration tests, and local development without coupling your tests to specific HTTP client implementations.
With over 9.8 million weekly downloads, MSW has become a standard tool for frontend and full-stack teams who need reliable API mocking. It's particularly valuable for organizations practicing API-first development, where frontend and backend teams work in parallel, or when testing edge cases and error states that are difficult to reproduce with real backends. The library's non-invasive approach means you can introduce mocking without refactoring existing code or changing how your application makes requests.
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
import { setupWorker } from 'msw/browser';
// Define request handlers
const handlers = [
http.get('/api/users/:id', ({ params }) => {
const { id } = params;
return HttpResponse.json({
id,
name: 'John Doe',
email: `user${id}@example.com`
});
}),
http.post('/api/users', async ({ request }) => {
const newUser = await request.json();
return HttpResponse.json(
{ id: '123', ...newUser },
{ status: 201 }
);
}),
http.get('/api/posts', () => {
return HttpResponse.json([
{ id: 1, title: 'First Post' },
{ id: 2, title: 'Second Post' }
]);
})
];
// For Node.js testing (Jest, Vitest, etc.)
const server = setupServer(...handlers);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
// For browser usage
// const worker = setupWorker(...handlers);
// worker.start();
// Test example
test('fetches user by id', async () => {
const response = await fetch('/api/users/42');
const user = await response.json();
expect(user.id).toBe('42');
expect(user.name).toBe('John Doe');
});
// Override handler for specific test
test('handles user not found', async () => {
server.use(
http.get('/api/users/:id', () => {
return HttpResponse.json(
{ error: 'User not found' },
{ status: 404 }
);
})
);
const response = await fetch('/api/users/999');
expect(response.status).toBe(404);
});Frontend development against unfinished APIs: When backend endpoints are still in development, define MSW handlers matching the API contract so frontend engineers can build features without blocking. The same handlers can later serve as integration test fixtures.
Testing error scenarios and edge cases: Simulate network failures, 500 errors, malformed responses, or slow connections that are difficult to trigger reliably against real services. MSW lets you test how your application handles these conditions without complex backend setup.
Isolating component and integration tests: Run tests against mocked APIs instead of test databases or staging environments, eliminating flakiness from external dependencies. Tests execute faster and remain deterministic because network behavior is fully controlled.
Local development without backend dependencies: Work on features entirely offline or without running backend services locally. MSW responds to requests in the browser DevTools network tab, making debugging feel identical to working with real APIs.
API contract validation and regression testing: Record real API responses and replay them in tests to detect breaking changes. Teams can use tools like The Source Library to generate MSW handlers from OpenAPI specs, ensuring mocks stay synchronized with API contracts.
npm install mswpnpm add mswbun add msw