Storybook wiring for Svelte CSF
This page covers msw-storybook-addon 3, which needs Storybook 9 or later, with msw 3 and @storybook/addon-svelte-csf. SvelteKit 3 runs on Vite 8, which no 9.x @storybook/sveltekit accepts: use Storybook 10 with a release whose Vite peer includes 8 (pnpm view @storybook/sveltekit@10 peerDependencies.vite). On Vitest 5, the Vitest storybook project needs Storybook 10, the first major whose @storybook/addon-vitest peers on Vitest 5; pick a release whose peer range includes it (pnpm view @storybook/addon-vitest@10 peerDependencies.vitest lists every 10.x release).
Contents
- Setup order
- Upstream sources that mislead a Svelte reader
- The
preview.tsloader - Where the baseline lives
- Per-story overrides
- Leaving the deprecated CSF 3 path
- What the addon's codemod will not do for
.stories.svelte
Setup order
- Install both packages:
pnpm add -D msw msw-storybook-addon - Register
mswLoader(setup)in.storybook/preview.ts, with the baseline handlers in itssetupWorker(...)(thepreview.tsloader, where the baseline lives). The Storybook handler set comes from your mocks index (handlers reference, one handler set per surface). Add".storybook/**/*.ts"to the tsconfigincludethat yourcheckscript uses, or nothing inpreview.tsis type-checked; a plain".storybook"entry matches no file - Serve the worker script to Storybook:
msw()in the Vite config servesstorybook dev(open/mockServiceWorker.json its origin to confirm); a built Storybook needs a committed file in Vite'spublicDir(the worker-script bullets under thepreview.tsloader) - Override per story with
beforeEach={({ msw }) => msw.use(...)}on<Story>(per-story overrides) - Run
pnpm exec vitest run --project storybook --silent=false(storybookbeing your storybook project's name; append a story file<file>to narrow it) and fix every unhandled-request warning, then take the three runs from the skill's Verify section
Upstream sources that mislead a Svelte reader
- The addon's README and MIGRATION.md route you to CSF Next, which
@storybook/addon-svelte-csfdoes not support:definePreviewis missing from the Svelte renderer (pnpm view @storybook/svelte exportslists no./preview). Do not runstorybook automigrate csf-factories, which the addon's codemod suggests on exit - The custom-setup examples in the addon's README and MIGRATION.md write
worker.start({ onUnhandledRequest: 'bypass' })on asetupWorker()without handlers; msw 3 ignores that key, so writeonUnhandledFrameand pass your baseline tosetupWorker(...) - MIGRATION.md says the default setup "ignores common asset and Storybook-internal requests, so custom
onUnhandledRequestfunctions written to silence those warnings are likely not needed anymore". On msw 3 that filter sits in the ignoredonUnhandledRequestcallback, so keep your ownonUnhandledFramefilter (thepreview.tsloader) - The README's "Global handlers" section puts shared handlers in a preview-level
beforeEach({ msw }). On themswLoader()path thatbeforeEachruns after the loader applies each story'sparameters.mswand shadows every such override, so keep the baseline insetupWorker(...)(where the baseline lives) - The README asks for
msw@2.x(Install) andnpx msw init ./public --save(Generate the worker script): the addon's peer range ismsw >=2, so msw 3 installs; on SvelteKit a committed worker script goes instatic/, and with themsw/vitepluginstorybook devneeds none (worker-script bullets under thepreview.tsloader) - Storybook's MSW page can show a different addon or msw major than you run, for example
graphqlimported frommsw, which msw 3 exports only frommsw/graphql; compare its imports with your installed majors before copying from it - Storybook's MSW page runs the addon codemod as
npx msw-storybook-migrate. Do not run that: current 3.x releases ship the codemod as themsw-storybook-addonbin (the first 3.x releases named itmsw-storybook-migrate, with nomigratesubcommand), and without a local bin of that namenpxfetches the npm packagemsw-storybook-migrate, which belongs to an unrelated publisher. Runpnpm exec msw-storybook-addon migrate --dry-runinstead, which fails rather than fetching when the bin is missing - msw's Storybook page shows
addons: ['msw-storybook-addon'], a baremswLoader()(the default setup, no baseline),npx msw init ./public --saveandparameters.mswoverrides. Apply the same corrections as for the README: your own setup with the baseline andonUnhandledFrame,static/on SvelteKit, andbeforeEachfor new overrides
The preview.ts loader
// .storybook/preview.ts
import { setupWorker } from "msw/browser";
import { mswLoader } from "msw-storybook-addon/csf3";
import { storybookHandlers } from "../src/mocks";
async function setup() {
const worker = setupWorker(...storybookHandlers); // the baseline resetHandlers() restores to
await worker.start({ onUnhandledFrame: "warn", quiet: true });
return worker;
}
export default {
loaders: [mswLoader(setup)],
};Wire the loader like this:
- Pass a setup function like this one: the addon's built-in default setup passes
onUnhandledRequest, which msw 3 ignores - Keep
quiet: truein it for the same console output: your setup replaces the default, which starts the worker withquiet: true - Filter Storybook's own requests in your own
onUnhandledFramecallback (below). Understorybook dev, switching to a story in another file imports its.stories.svelteand.sveltemodules after the worker has started, and they warn: msw's built-in strategy skips only common assets, which covers.jsand.htmlpaths but not.svelte. The default setup's filter lived in its ignoredonUnhandledRequestcallback, and the addon does not export it (isCommonStorybookRequest). In the Vitest storybook project none of Storybook's requests reach the callback
import { isCommonAssetRequest } from "msw";
// the addon's Storybook-request pattern from its src/addon.ts, plus .svelte modules
const storybookRequest =
/\.eot$|\.mdx$|sb-common-assets|__webpack_hmr|iframe.html|sb-vite|@vite|@react-refresh|\/virtual:|\.stories\.|\.svelte$/;
// inside the setup function passed to mswLoader(...)
await worker.start({
quiet: true,
onUnhandledFrame({ frame, defaults }) {
// a WebSocket a story opened: Storybook's and Vite's own sockets open before the worker starts
if (frame.protocol !== "http") return defaults.warn();
const { request } = frame.data as { request: Request };
// a custom callback replaces msw's built-in asset skip
if (isCommonAssetRequest(request)) return;
// the pathname, so ?svelte&type=style&lang.css and ?t= queries still match
if (storybookRequest.test(new URL(request.url).pathname)) return;
defaults.warn();
},
});The addon's own pattern ends at \.stories\., so component modules such as /src/stories/Button.svelte still warn; |\.svelte$ covers them. Test it against the pathname: a component's <style> block loads as /src/lib/Thing.svelte?svelte&type=style&lang.css, which \.svelte$ misses on the full URL. The isCommonAssetRequest check also silences API paths ending in .json and other common extensions (msw-3 reference, unhandled-frame item 4), so an unmocked /api/items.json does not warn here.
The callback warns on every unhandled WebSocket frame, with no URL filter. Under storybook dev, Storybook's and Vite's own sockets open before mswLoader starts the worker, so they never reach the callback, and after a dev-server restart Vite reloads the page rather than reconnecting through the worker. An unmocked socket a story opens does reach it, and an early return for non-HTTP frames would let it connect with no warning.
Around the preview.ts loader:
- The worker script:
- a Vite config that loads the
msw/viteplugin (as the@msw/sveltekitadd-on sets up) serves it to a Vitest storybook project whose config loads or inherits that plugin - the plugin also serves it to
storybook dev: open/mockServiceWorker.json its origin to confirm - a
storybook buildnever contains it from the plugin, which emits it only next to bundles that importvirtual:msw - for a built Storybook, when
storybook devdoes not serve it, or without the plugin, commit it (pnpm exec msw init static --saveon SvelteKit,publicon Vite). Storybook's Vite builder copies Vite'spublicDir, sostorybook devserves the committed file andstorybook buildcontains it without astaticDirsentry; addstaticDirsin.storybook/main.tsonly for a script outsidepublicDir
- a Vite config that loads the
- The Vitest storybook project serves a committed worker script from Vite's
publicDirtoo, so setpublicDirwhen the script lives outsidepublic/(addon-vitest FAQ). On SvelteKit,sveltekit()already setspublicDirto itsfiles.assetsoption (static/by default), so a Vitest storybook project that inherits it needs no setting - Listing the addon in
.storybook/main.tsaddonsis harmless on thismswLoader()path: the loader setscontext.mswbefore anybeforeEachruns, and the addon's own annotations then step aside - Types:
msw-storybook-addon/csf3typesparameters.msw; every entry point typescontext.mswforbeforeEach({ msw }), andmsw-storybook-addon/typescarries that alone. The addon README's "Types" section asks CSF 3.0 projects to addmsw-storybook-addon/csf3tocompilerOptions.types; a.storybook/preview.tsthat imports/csf3already brings theparameters.mswtypes into the compilation, so the entry is needed only when the stories compile without it, for example whentsconfig.json'sincludeleaves out.storybook/**/*.ts, which SvelteKit's defaultincludedoes (Setup order step 2 adds it). Without thatincludeentry on SvelteKit, add/csf3next to$app/types, which SvelteKit requires in that array:"types": ["$app/types", "msw-storybook-addon/csf3"] svelte-5:storybook-vitestownsoptimizeDepsfor the Vitest storybook project- Stories rendered in Node.js work through a setup function that starts
setupServerinstead (MIGRATION.md); the addon has no built-in Node.js support, and "The setup function is typed to return a browser worker, so the Node.js branch needs a type cast" (MIGRATION.md) - msw 3 intercepts navigations, so under
storybook deva tab showing a worker-controllediframe.htmlthat navigates to the manager URL warnsGET /?path=..., and the manager's stories can stay on "loading". Open the manager URL in a new page, for example a new Playwright page, instead of navigating the preview tab to it
Where the baseline lives
Baseline handlers go in setupWorker(...), never in preview.parameters.msw, where the README's CSF 3 example puts them:
mswLoaderruns the setup function once and caches the worker- Before each story it calls
resetHandlers(), which restores thesetupWorkerbaseline, thenworker.use(...)with the story'sparameters.msw, so story handlers sit in front of the baseline - Storybook's
combineParametersoverwrites arrays and deep-merges only plain objects. A story that declaresmsw: [...]ormsw: { handlers: [...] }drops a project-levelparameters.mswwith no warning, and only for the stories that override something. The exception is the addon's named-Record form,msw: { handlers: { auth: [...], feed: [...] } }, a plain object that merges by key, so project-level groups survive unless a key collides
Per-story overrides
Write new overrides with beforeEach({ msw }): MIGRATION.md deprecates parameters.msw in its favour, and createPreviewAnnotations reads only beforeEach. Existing parameters.msw overrides keep working on the mswLoader() path, so leave them until you switch paths.
parameters={{ msw: { handlers: [...] } }}on<Story>: the addon's MIGRATION.md calls both this and the CSF 3 loader API deprecated, and saysparameters.msw"keeps working in v3 in CSF 3.0 setups only"; it keeps working on themswLoader()path, which Svelte CSF uses. Nothing warns at runtime aboutparameters.msw; the loader's deprecation warning fires only whenparameters.csfFactory === true, and its text is aboutmswLoaderbeforeEach={({ msw }) => msw.use(...)}on<Story>:mswLoader()runs duringloaders, before meta and storybeforeEach, socontext.mswis set there
Leaving the deprecated CSF 3 path
MIGRATION.md: "The loader API is deprecated and will be removed in the next major release." The addon's own mswLoader JSDoc is narrower: "This is the supported integration for CSF 3.0 projects", deprecated "when using CSF Next", and its runtime warning fires only for CSF Next. createPreviewAnnotations is the path off the loader either way. createPreviewAnnotations from msw-storybook-addon/preview returns plain project annotations: a beforeEach that assigns context.msw and resets handlers after each story. It needs no definePreview and no deprecated API, and it spreads straight into a CSF 3 preview default export.
Baseline handlers, beforeEach({ msw }) overrides and the per-story reset all work on it. It ignores parameters.msw without a warning, so adopting it without rewriting your stories drops every existing override with no error, and a loader that generates handlers into parameters.msw stops applying them (handlers reference). The full switch:
preview.tsspreadscreatePreviewAnnotations(setup)instead of registeringmswLoader(). The spread brings abeforeEach, so a preview that already definesbeforeEachloses one of the two, depending on which comes later. Pass both as an array instead, the addon's first, so yours seescontext.msw.createPreviewAnnotationstypes itsbeforeEachas a hook, an array orundefined, so flatten it into the array:// @storybook/sveltekit on SvelteKit, @storybook/svelte-vite otherwise import type { Preview, StoryContext } from "@storybook/sveltekit"; import { createPreviewAnnotations } from "msw-storybook-addon/preview"; // setup: the function from the preview.ts loader snippet const msw = createPreviewAnnotations(setup); function yourBeforeEach(context: StoryContext) { // context.msw is set here } const preview: Preview = { beforeEach: [msw.beforeEach ?? [], yourBeforeEach].flat(), }; export default preview;every per-story override becomes
beforeEach={({ msw }) => msw.use(...)}on<Story>Add
msw-storybook-addon/previewtooptimizeDeps.include(svelte-5:storybook-vitestownsoptimizeDeps). The Vitest storybook project pre-bundles/csf3itself but not/preview: without the entry, a cold run optimizes it mid-run, reloads, and every story file fails withVitest failed to find the current suite(see also the addon-vitest docs on dependency optimization)remove the addon from
addonsin.storybook/main.ts, although the README's CSF 3 setup lists it there and the addon's codemod adds it
Step 4 matters on this path: a listed addon brings its own preview annotations, createPreviewAnnotations() with the default setup and a worker without handlers. Its beforeEach and yours share one module-level worker and return early once context.msw is set, so whichever runs first decides the worker, and your setup with the baseline handlers may never run.
Staying on mswLoader() with parameters.msw is the smaller diff and works on addon 3; switch before the addon's next major.
What the addon's codemod will not do for .stories.svelte
The addon's codemod (pnpm exec msw-storybook-addon migrate) keeps mswLoader() in the preview but rewrites parameters.msw in JS/TS stories, and at preview level, to beforeEach({ msw }). Its default glob is **/*.{stories,story}.{js,jsx,ts,tsx,mjs,mjsx,mts,mtsx}, with no .svelte; --help prints it, and --dry-run previews a run.
On a Svelte-only project it migrates the config and reports No story files matched glob. Adding .svelte to --glob hides the failure: the file matches, the JS/TS AST pass cannot parse Svelte markup, and the transform swallows the failure and returns no change, so the run counts the file as already up to date with no error and no entry in the skipped-stories report. A silent run there means the file was not migrated, and the .stories.svelte files stay on parameters.msw.