{"id":16129,"library":"msw","title":"Mock Service Worker","description":"Mock Service Worker (MSW) is a powerful and seamless library for intercepting and mocking REST and GraphQL API requests directly at the network level, in both browser and Node.js environments. Unlike traditional mocking libraries that patch client-side request utilities, MSW leverages the Service Worker API in browsers and a custom `http` interception module in Node.js. This approach allows applications to run against mock data without any code changes, making it ideal for consistent mocking across development, unit, integration, and end-to-end testing, as well as debugging. The current stable version is 2.13.4, with frequent minor and patch releases, often several times a month, indicating active development. Its key differentiator is providing deviation-free mocking by intercepting actual network requests, ensuring a high fidelity simulation of real API interactions.","status":"active","version":"2.13.4","language":"javascript","source_language":"en","source_url":"https://github.com/mswjs/msw","tags":["javascript","api","mock","mocking","worker","prototype","server","service","handler","typescript"],"install":[{"cmd":"npm install msw","lang":"bash","label":"npm"},{"cmd":"yarn add msw","lang":"bash","label":"yarn"},{"cmd":"pnpm add msw","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency for TypeScript projects (ships types). While not strictly required for JavaScript-only projects, it's essential for type-safety and optimal developer experience in TypeScript.","package":"typescript","optional":true}],"imports":[{"note":"Used for browser environments. MSW v2+ is an ESM-only package, so `require` syntax for `setupWorker` will fail. The entry point also changed from `msw` to `msw/browser` in v2.","wrong":"const { setupWorker } = require('msw')","symbol":"setupWorker","correct":"import { setupWorker } from 'msw/browser'"},{"note":"Used for Node.js environments (e.g., testing). MSW v2+ requires importing from `msw/node`. `require` syntax will also fail.","wrong":"import { setupServer } from 'msw'","symbol":"setupServer","correct":"import { setupServer } from 'msw/node'"},{"note":"The `http` object is used for defining REST API request handlers. In MSW v2, the `rest` object from v1 was renamed to `http` for clarity and consistency.","wrong":"import { rest } from 'msw'","symbol":"http","correct":"import { http } from 'msw'"},{"note":"Provides utilities for constructing mock HTTP responses, including status, headers, and body. Commonly used within handler resolvers.","symbol":"HttpResponse","correct":"import { HttpResponse } from 'msw'"}],"quickstart":{"code":"import { setupWorker, http, HttpResponse } from 'msw';\n\n// Define handlers for your API requests\nconst handlers = [\n  http.get('https://example.com/api/user/:userId', ({ params }) => {\n    const { userId } = params;\n    if (userId === '123') {\n      return HttpResponse.json(\n        { id: '123', name: 'John Doe', email: 'john.doe@example.com' },\n        { status: 200 }\n      );\n    }\n    return HttpResponse.json({ message: 'User not found' }, { status: 404 });\n  }),\n  http.post('https://example.com/api/users', async ({ request }) => {\n    const newUser = await request.json();\n    console.log('New user creation request:', newUser);\n    return HttpResponse.json({ id: 'new-id', ...newUser }, { status: 201 });\n  })\n];\n\n// Create a service worker instance\nconst worker = setupWorker(...handlers);\n\n// Register the Service Worker in the browser\nworker.start({\n  onUnhandledRequest: 'warn' // Configure behavior for unhandled requests\n});\n\nconsole.log('MSW service worker started.');\n\n// Example usage: Make a fetch request that will be intercepted by MSW\nasync function demonstrateMocking() {\n  try {\n    console.log('Fetching user 123...');\n    const userResponse = await fetch('https://example.com/api/user/123');\n    const userData = await userResponse.json();\n    console.log('Fetched user (mocked):', userData);\n\n    console.log('Creating a new user...');\n    const createUserResponse = await fetch('https://example.com/api/users', {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json' },\n      body: JSON.stringify({ name: 'Jane Smith', email: 'jane.smith@example.com' })\n    });\n    const newUserData = await createUserResponse.json();\n    console.log('Created user (mocked):', newUserData);\n  } catch (error) {\n    console.error('Fetch error:', error);\n  }\n}\n\ndemonstrateMocking();","lang":"typescript","description":"This quickstart demonstrates setting up a browser-based Mock Service Worker to intercept and respond to HTTP GET and POST requests, followed by actual `fetch` calls that are intercepted by the mock server."},"warnings":[{"fix":"Migrate your project to use ECMAScript Modules (ESM) syntax (`import ... from '...'`) and ensure your `package.json` has `\"type\": \"module\"` or uses `.mjs` file extensions. Update your bundler/build configuration if necessary.","message":"MSW v2 is an ESM-only package and no longer supports CommonJS (`require`). All imports must use ESM syntax (`import`).","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Replace `rest.get`, `rest.post`, etc., with `http.get`, `http.post`, and similar for other HTTP methods. Review the official migration guide for other API changes in v2, particularly for GraphQL handlers.","message":"The `rest` object for defining HTTP handlers was renamed to `http` in MSW v2. Similarly, the `graphql` object also underwent changes in its API.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Update your import statements: `import { setupWorker } from 'msw'` becomes `import { setupWorker } from 'msw/browser'` for browser usage, and `import { setupServer } from 'msw'` becomes `import { setupServer } from 'msw/node'` for Node.js usage.","message":"The package entry points for browser and Node.js setups changed in MSW v2. Browser setup now imports from `msw/browser` and Node.js from `msw/node`.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Run `npx msw init <PUBLIC_DIR_PATH>` to automatically generate/update the worker script. Verify that the `mockServiceWorker.js` file is accessible at the root of your application (e.g., `http://localhost:3000/mockServiceWorker.js`). If using a custom path, ensure `setupWorker` is configured with `serviceWorker.url`.","message":"Ensuring the Service Worker script (`mockServiceWorker.js`) is correctly served at the root of your application's public directory is crucial for browser environments. Incorrect paths or server configurations can prevent the worker from registering.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Wrap your `setupServer` calls in test framework lifecycle hooks:\n`beforeAll(() => server.listen());`\n`afterEach(() => server.resetHandlers());`\n`afterAll(() => server.close());`\nRefer to MSW documentation for specific test runner integrations.","message":"When using MSW in Node.js test environments (e.g., Jest, Vitest), it's important to properly set up the lifecycle hooks (`beforeAll`, `afterAll`, `afterEach`) to start and stop the server and reset handlers.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Ensure you are using `import { setupWorker } from 'msw/browser'` and that your project is configured for ESM. For Node.js, use `import { setupServer } from 'msw/node'`.","cause":"Attempting to use CommonJS `require` or incorrect ESM import syntax for MSW v2, which is ESM-only, or importing `setupWorker` from the wrong entry point (`msw` instead of `msw/browser`).","error":"SyntaxError: Named export 'setupWorker' not found. The requested module 'msw' does not provide an export named 'setupWorker'"},{"fix":"Verify that `mockServiceWorker.js` is present in your public directory and accessible. Run `npx msw init <PUBLIC_DIR_PATH>` to re-initialize it. Check your web server configuration to ensure it serves static files correctly from the root path. If using a custom path, specify it in `setupWorker({ serviceWorker: { url: '/custom/path/mockServiceWorker.js' } })`.","cause":"The `mockServiceWorker.js` file is not found at the expected path (usually the public root) by the browser when `worker.start()` is called.","error":"Failed to register a Service Worker: A bad HTTP response code (404) was received when fetching the script."},{"fix":"Ensure `setupServer` is correctly imported as `import { setupServer } from 'msw/node'` and that the `server` variable is assigned the result of `setupServer(...)`.","cause":"The `server` object returned by `setupServer` is either undefined or not properly instantiated, often due to incorrect import or setup in a Node.js environment.","error":"TypeError: Cannot read properties of undefined (reading 'listen') at server.listen"},{"fix":"Replace `rest.get`, `rest.post`, `rest.put`, `rest.patch`, `rest.delete` with their `http` equivalents (e.g., `http.get`, `http.post`).","cause":"Using the deprecated `rest` object from MSW v1 instead of the `http` object for defining request handlers in an MSW v2 environment.","error":"Error: [MSW] The 'rest' handler is deprecated and will be removed in the next major version. Please use 'http' instead."}],"ecosystem":"npm"}