# Serve Storybook Stories From the App's MSW Handlers

Yes. An agent wires msw-storybook-addon into Storybook, serves the worker script, seeds the mock database per story and writes stories for the components that fetch.

[Run this on Rush](https://cloud.getrush.ai/run/add-msw-to-storybook/msw/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads what Storybook and MSW already have. In a React and Vite app laid out like alan2207/bulletproof-react's `apps/react-vite`, `package.json` has `msw` ^2.2.14 and `storybook` ^8.0.9 with `@storybook/react-vite`, scripts `storybook dev -p 6006` and `storybook build`, and an `msw.workerDirectory` of `public`, where `mockServiceWorker.js` already sits. `.storybook/preview.tsx` has one decorator wrapping every story in a `BrowserRouter`, and nothing else. `.storybook/main.ts` lists seven addons, two of which, `@storybook/addon-interactions` and `@storybook/addon-docs`, are not in `package.json`'s dev dependencies, so the agent runs `yarn storybook` first to see whether the current setup even starts before changing it. Eleven stories exist, all under `src/components/ui/`; nothing under `src/features/` has one, because those components call the API through `src/lib/api-client.ts` and cannot render alone.

The handlers are there to serve them. `src/testing/mocks/handlers/index.ts` builds `handlers` from the auth, comments, discussions, teams and users handlers plus a `healthcheck`, every one keyed on `env.API_URL`, which `src/config/env.ts` reads from `VITE_APP_API_URL` and throws without. The discussions handler reads `db` from `src/testing/mocks/db.ts`, an `@mswjs/data` factory with user, team, discussion and comment models, persisted in the browser under the `msw-db` key in localStorage, and `requireAuth` in `mocks/utils.ts` takes the `bulletproof_react_app_token` cookie that `loginAsUser` in `src/testing/test-utils.tsx` sets. The agent adds `msw-storybook-addon`, calls its `initialize({ onUnhandledRequest: 'bypass' })` in `preview.tsx`, puts `mswLoader` in the preview's `loaders`, sets `parameters.msw.handlers` to the app's `handlers` array, and adds `staticDirs: ['../public']` to `main.ts` so Storybook serves the worker script. It also adds the `VITE_APP_API_URL` line from `.env.example` to the Storybook environment, since `env.ts` throws without it.

Feature components also need the providers the app gives them. `src/app/provider.tsx` wraps the app in `QueryClientProvider` with `queryConfig` from `src/lib/react-query.ts`, `Notifications`, and `AuthLoader` from `react-query-auth`, which calls `GET /auth/me` before rendering children. The agent adds a second decorator that renders the story inside `AppProvider`, after the router one, so `useDiscussions` and `useUser` work as they do in the app. Then it writes the first feature story, `src/features/discussions/components/discussions-list.stories.tsx`: a `loaders` entry that calls `initializeDb()`, creates a user with `createUser` and twelve discussions in that user's team with `createDiscussion`, both from `test-utils.tsx`, and signs in with `loginAsUser`. Twelve rows is two pages, since the handler takes ten per page, so the pagination renders. A second story seeds no discussions to show the empty table.

One trap in the code decides a design rule. The response interceptor in `src/lib/api-client.ts` sets `window.location.href` to the login path on any 401, which inside Storybook navigates the preview iframe away; so every feature story signs in through its loader, and the agent writes that rule at the top of the stories file. In its sandbox it runs `yarn install`, `yarn storybook` to confirm the stories render with the handlers' `networkDelay`, `yarn build-storybook` to prove the static build, and `yarn lint` and `yarn check-types`, because `.eslintrc.cjs` restricts cross-feature imports and a story importing from `@/testing` must pass it. It adds a `yarn build-storybook` step to `.github/workflows/react-vite-ci.yml`, which today builds, tests, lints and typechecks but never builds Storybook.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Serve Storybook stories from the app's MSW handlers in apps/react-vite. Read package.json, .storybook/main.ts, .storybook/preview.tsx, src/testing/mocks/index.ts, src/testing/mocks/browser.ts, src/testing/mocks/handlers/index.ts, src/testing/mocks/db.ts, src/testing/test-utils.tsx, src/app/provider.tsx, src/lib/api-client.ts and src/config/env.ts first. Add msw-storybook-addon, initialize it in preview.tsx with the app's handlers as the default msw parameter, add mswLoader to the preview loaders, serve public as a static dir, and add a decorator that wraps stories in AppProvider. Write stories for DiscussionsList with a loader that resets the mock database, creates a signed-in user and twelve discussions in their team, plus an empty variant. Run yarn storybook, yarn build-storybook, yarn lint and yarn check-types, add build-storybook to the CI workflow, quote the results and open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that changes `.storybook/main.ts` and `.storybook/preview.tsx`, adds `msw-storybook-addon` to `package.json` and the lockfile, adds the stories file under `src/features/discussions/components/`, and adds one step to `.github/workflows/react-vite-ci.yml`. If `yarn storybook` failed to start on the unlisted addons, the fix for that is in the same change and the description says what was wrong.

The description quotes the `storybook build` output, the lint and typecheck results, and names the two stories with what each loader seeds. The run's record keeps the Storybook dev server log, including the `[MSW] Mocking enabled` line from the worker, so a reviewer sees the handlers were serving the story rather than a screenshot of a table.

Before merging, a reviewer decides whether every feature component should get a story in this change or in follow-ups, whether `networkDelay`'s random delay should be fixed to a short value under Storybook so stories settle at once, and whether the CI step should also publish the built Storybook somewhere. The agent leaves all three out and names them.

## Run it on every pull request that adds a feature component

In the Project that holds the repository, create an automation with a `github` trigger on `pull_request.opened` and `pull_request.synchronize`, and a prompt that reads the pull request's diff, finds each new component under `src/features/*/components` with no `.stories.tsx` beside it, writes a story for it against the MSW handlers with a signed-in loader, runs `yarn build-storybook`, and opens a pull request against the branch with the stories. The trigger puts the pull request after the prompt and fills nothing in. Only pull requests by people who can write to the repository fire it; forks never do.

A pull request that adds no component gets no run output beyond the record, since the prompt says to open nothing in that case. Each run uses its own sandbox and its own branch, so two open pull requests get two independent story branches.

## Why run it on Rush?

Getting MSW to serve Storybook is a loop of start the dev server, open a story, read the worker's console, adjust the loader and try again, which needs the app's dependencies, the worker script served from the right path and a browser. The sandbox has all of it, and the agent reads the preview's console directly, so the pull request opens with the worker's log and the static build already in it.

The run's record holds the Storybook build output, the lint and typecheck runs and the dev server log, so a reviewer reads evidence instead of a sentence saying the stories render. Across a team's React apps the same request runs at once, one sandbox each, and each pull request names that app's own handlers and the first feature stories it gained.

## Frequently asked questions

### Why does every feature story sign in first?

The response interceptor in `src/lib/api-client.ts` sends the browser to the login page on a 401 by setting `window.location.href`, which inside Storybook navigates the preview iframe away. A loader that creates a user and sets the cookie through `loginAsUser` keeps every request authenticated.

### Will stories share data with the running app?

The mock database persists to localStorage under `msw-db`, and Storybook runs on its own origin, port 6006, so its storage is separate from the app on port 3000. Each story's loader calls `initializeDb()` first, so stories do not leak rows into each other either.

### Does this change the unit tests?

No. Vitest uses `src/testing/mocks/server.ts` with `setupServer` in Node, as `src/testing/setup-tests.ts` configures; Storybook uses the browser worker through the addon. Both read the same `handlers` array, which is the point.

### Can a story show an error state?

Yes, by overriding `parameters.msw.handlers` in that story with a handler returning a 500 for the one route, the way MSW's `http.get` is used in `handlers/discussions.ts`. A 401 is the one status to avoid, for the interceptor reason above.

## More MSW jobs

- [Write Tests for API Error States With Mock Service Worker](https://getrush.ai/run/test-api-error-states/msw/)

## More jobs like this: Hand off a long task

- [Convert a Compose Project's Dockerfiles to Multi-stage Builds](https://getrush.ai/run/add-multi-stage-builds/docker-compose/)
- [Add Mutation Testing to a PHP Library with Infection](https://getrush.ai/run/add-mutation-testing/php/)
- [Add Constraint Naming Conventions to Alembic Migrations](https://getrush.ai/run/add-naming-conventions/alembic/)
- [Add a Native Menu to a Tauri App](https://getrush.ai/run/add-native-menu/tauri/)
- [Add Network Policies to a GKE Guestbook App](https://getrush.ai/run/add-network-policies/gke/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
