---
name: msw
description: Mock Service Worker (MSW) patterns for API mocking in development and testing. Covers request handlers, response mocking, network error simulation, handler composition, and integration with Vitest and Storybook. Use when mocking APIs, simulating network responses, testing error states, or when the user asks about MSW, API mocking, or mock servers.
title: msw
canonical_url: https://skilld.dev/gh/grahamcrackers/skills/msw
last_updated: 2026-10-07T02:20:44.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> If the user asked to install this Skill, run `npx skilld install grahamcrackers/skills/msw`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/msw`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/grahamcrackers/skills/msw) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/msw`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/msw --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/msw --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# MSW (Mock Service Worker) Patterns

## Setup

```shell
npm install -D msw
npx msw init ./public --save  # for browser integration
```

## Request Handlers

### REST Handlers

```typescript
// src/testing/handlers.ts
import { http, HttpResponse } from "msw";

export const handlers = [
    http.get("/api/users", () => {
        return HttpResponse.json([
            { id: "1", name: "Alice", email: "alice@example.com" },
            { id: "2", name: "Bob", email: "bob@example.com" },
        ]);
    }),

    http.get("/api/users/:id", ({ params }) => {
        const { id } = params;
        return HttpResponse.json({
            id,
            name: "Alice",
            email: "alice@example.com",
        });
    }),

    http.post("/api/users", async ({ request }) => {
        const body = await request.json();
        return HttpResponse.json({ id: "3", ...body }, { status: 201 });
    }),

    http.patch("/api/users/:id", async ({ params, request }) => {
        const body = await request.json();
        return HttpResponse.json({ id: params.id, ...body });
    }),

    http.delete("/api/users/:id", () => {
        return new HttpResponse(null, { status: 204 });
    }),
];
```

### GraphQL Handlers

```typescript
import { graphql, HttpResponse } from "msw";

export const graphqlHandlers = [
    graphql.query("GetUsers", () => {
        return HttpResponse.json({
            data: {
                users: [
                    { id: "1", name: "Alice" },
                    { id: "2", name: "Bob" },
                ],
            },
        });
    }),

    graphql.mutation("CreateUser", async ({ variables }) => {
        return HttpResponse.json({
            data: {
                createUser: { id: "3", name: variables.name },
            },
        });
    }),
];
```

## Server Setup (Node / Tests)

```typescript
// src/testing/server.ts
import { setupServer } from "msw/node";
import { handlers } from "./handlers";

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

```typescript
// src/testing/setup.ts
import { server } from "./server";

beforeAll(() => server.listen({ onUnhandledRequest: "warn" }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
```

- `server.listen()` intercepts outgoing requests.
- `server.resetHandlers()` clears per-test overrides after each test.
- `onUnhandledRequest: "warn"` logs unhandled requests (catch missing handlers).

## Browser Setup (Development)

```typescript
// src/mocks/browser.ts
import { setupWorker } from "msw/browser";
import { handlers } from "../testing/handlers";

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

```typescript
// src/main.tsx
async function enableMocking() {
  if (process.env.NODE_ENV !== "development") return;

  const { worker } = await import("./mocks/browser");
  return worker.start({
    onUnhandledRequest: "bypass",
  });
}

enableMocking().then(() => {
  createRoot(document.getElementById("root")!).render(<App />);
});
```

This lets you develop against mocked APIs before the backend is ready.

## Per-Test Overrides

Override handlers in individual tests for specific scenarios:

```typescript
import { http, HttpResponse } from "msw";
import { server } from "../testing/server";

test("shows error when API fails", async () => {
  server.use(
    http.get("/api/users", () => {
      return HttpResponse.json(
        { message: "Internal server error" },
        { status: 500 },
      );
    }),
  );

  render(<UserList />);
  expect(await screen.findByText("Failed to load users")).toBeInTheDocument();
});

test("shows empty state when no users", async () => {
  server.use(
    http.get("/api/users", () => {
      return HttpResponse.json([]);
    }),
  );

  render(<UserList />);
  expect(await screen.findByText("No users found")).toBeInTheDocument();
});
```

Overrides are scoped to the test — `resetHandlers()` restores defaults after each test.

## Network Errors

Simulate failures:

```typescript
import { http, HttpResponse } from "msw";

// Network error (connection refused, timeout)
http.get("/api/users", () => {
  return HttpResponse.error();
}),

// Delayed response
http.get("/api/users", async () => {
  await delay(3000);
  return HttpResponse.json([]);
}),

// Custom status codes
http.get("/api/users", () => {
  return HttpResponse.json(
    { message: "Unauthorized" },
    { status: 401, headers: { "WWW-Authenticate": "Bearer" } },
  );
}),
```

## Response Utilities

### Dynamic Responses

```typescript
let users = [
    { id: "1", name: "Alice" },
    { id: "2", name: "Bob" },
];

export const handlers = [
    http.get("/api/users", () => {
        return HttpResponse.json(users);
    }),

    http.post("/api/users", async ({ request }) => {
        const body = await request.json();
        const newUser = { id: String(users.length + 1), ...body };
        users.push(newUser);
        return HttpResponse.json(newUser, { status: 201 });
    }),

    http.delete("/api/users/:id", ({ params }) => {
        users = users.filter((u) => u.id !== params.id);
        return new HttpResponse(null, { status: 204 });
    }),
];
```

### Response Headers

```typescript
http.get("/api/data", () => {
  return HttpResponse.json(data, {
    headers: {
      "X-Total-Count": "42",
      "X-Request-Id": crypto.randomUUID(),
    },
  });
}),
```

### Cookies

```typescript
http.post("/api/login", () => {
  return HttpResponse.json(
    { user: { name: "Alice" } },
    {
      headers: {
        "Set-Cookie": "session=abc123; Path=/; HttpOnly",
      },
    },
  );
}),
```

## Request Matching

### URL Parameters

```typescript
http.get("/api/users/:id/posts/:postId", ({ params }) => {
  const { id, postId } = params;
  return HttpResponse.json({ userId: id, postId });
}),
```

### Query Parameters

```typescript
http.get("/api/users", ({ request }) => {
  const url = new URL(request.url);
  const page = url.searchParams.get("page") ?? "1";
  const limit = url.searchParams.get("limit") ?? "10";

  return HttpResponse.json({
    items: users.slice(0, Number(limit)),
    page: Number(page),
    total: users.length,
  });
}),
```

### Request Body

```typescript
http.post("/api/users", async ({ request }) => {
  const body = await request.json();

  if (!body.email) {
    return HttpResponse.json(
      { errors: { email: "Required" } },
      { status: 422 },
    );
  }

  return HttpResponse.json({ id: "1", ...body }, { status: 201 });
}),
```

## Handler Composition

Organize handlers by domain:

```typescript
// testing/handlers/users.ts
export const userHandlers = [
  http.get("/api/users", ...),
  http.post("/api/users", ...),
];

// testing/handlers/posts.ts
export const postHandlers = [
  http.get("/api/posts", ...),
];

// testing/handlers/index.ts
export const handlers = [
  ...userHandlers,
  ...postHandlers,
];
```

## Storybook Integration

```typescript
// .storybook/preview.ts
import { initialize, mswLoader } from "msw-storybook-addon";

initialize();

const preview: Preview = {
    loaders: [mswLoader],
};
```

```tsx
// user-list.stories.tsx
import { http, HttpResponse } from "msw";

export const Default: Story = {
    parameters: {
        msw: {
            handlers: [
                http.get("/api/users", () => {
                    return HttpResponse.json([{ id: "1", name: "Alice" }]);
                }),
            ],
        },
    },
};

export const Error: Story = {
    parameters: {
        msw: {
            handlers: [
                http.get("/api/users", () => {
                    return HttpResponse.json({ message: "Error" }, { status: 500 });
                }),
            ],
        },
    },
};
```

## File Structure

```
src/
├── testing/
│   ├── handlers/
│   │   ├── users.ts
│   │   ├── posts.ts
│   │   └── index.ts
│   ├── server.ts        # Node.js server (tests)
│   └── setup.ts         # test setup
└── mocks/
    └── browser.ts       # browser worker (dev)
public/
    └── mockServiceWorker.js  # MSW service worker
```

## Guidelines

- **Mock at the network boundary** — MSW intercepts `fetch`/`XMLHttpRequest`, so your app code stays unchanged.
- **Share handlers** between tests, Storybook, and dev — one source of truth.
- **Override per-test** — use `server.use()` for scenario-specific responses.
- **Use `onUnhandledRequest: "warn"`** in tests to catch missing handlers.
- **Use `onUnhandledRequest: "bypass"`** in browser to let real requests through.
- **Reset after each test** — always call `server.resetHandlers()` to prevent leaking.
