5 January, 2024 | 2 min read

How to Set Up MSW 2.0 in a React Project With Vite

Step 1: Install MSW

npm install msw --save-dev
npx msw init ./public

This will install MSW into our project and copy the worker script into the public directory.

Step 2: Set Up The Handlers

Create a file to define your request handlers.

import { http, HttpResponse } from 'msw';
export const handlers = [
  // An example handler
  http.get('/user', () => {
    return HttpResponse.json({ name: 'John Maverick' });

Then, create a file to set up the handlers on the server and one for the browser. The browser file will be used when our app is running in the browser. The server file will be used by our tests.

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

export const server = setupServer(...handlers);
import { setupWorker } from 'msw/browser';
import { handlers } from './handlers';

export const worker = setupWorker(...handlers);

Step 3: Conditionally Enable Mocking

Update main.tsx to start the worker before rendering the app. We’ll only run this step in development so production is unaffection.

import React from 'react';
import ReactDOM from 'react-dom';
import { App } from './App';
async function enableMocking() {
  if (process.env.NODE_ENV !== 'development') {
  const { worker } = await import('./mocks/browser');
  // `worker.start()` returns a Promise that resolves
  // once the Service Worker is up and ready to intercept requests.
  return worker.start();
enableMocking().then(() => {
      <App />

Run the application in the browser, and you should see a confirmation message in the console in the Developer Tools.

[MSW] Mocking enabled.

Set Up MSW For Vitest Tests

In your test setup file, import and start the server.

import { server } from './mocks/node.js';

beforeAll(() => {

afterEach(() => {

afterAll(() => {

Follow me on Twitter to get updates on new posts.