How to setup MSW in a React project using Vite

Tl;dr: Sample Project with React, Vite and MSW

First of all, you must have a Vite project. After that, you can install MSW with the following command:

npm install msw --save-dev

Setup MSW

To setup MSW, you'll create a file called handlers.ts in the src directory or in any other fold. This file will contain all of your handlers:

// handlers.ts

import { rest } from "msw";

// This handler will intercept any rest request in your project.
export const handlers = [];


// handlers.ts

import { rest } from "msw";
export const handlers = [
    (_, res, ctx) => {
      return res(
          userId: 1,
          id: 1,
          title: "delectus aut autem",
          completed: false,

After that, two new files will be created, one that will intercept the browser request, and other, that will intercept the Node request. For example:

// server.ts
import { setupServer } from "msw/node";

import { handlers } from "./handlers";

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

import { handlers } from "./handlers";

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

Setup the application

With the files created, you can now setup the application. First, you'll import the browser.ts in the entrypoint file of your project. For example:

// main.tsx

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

import { App } from "@/App"; // The main component of the application.

// The root element where React will be mounted.
const root = createRoot(document.getElementById("root") as HTMLElement);

if (import.meta.env.MODE === "development") {
  // When development, setup the MSW.
  // import the worker (under the browser.ts file)
    .then(({ worker }) => {
      // Start the worker.
    .then(() => {
      // Render the application.
          <App />
} else {
  // Render the application in production without the MSW.
      <App />

Setup the tests

In your test setup, import the server.ts, and start the server. For example:

// setup-test.ts

import { server } from "./server";

beforeAll(() => {
  server.listen({ onUnhandledRequest: "error" });

afterEach(() => {

afterAll(() => {

Project example

You can find a project example in the following repository:

Useful links