plugins: [pluginMsw()]OpenAPI to MSW mock handler generator
@kubb/plugin-msw
Generates MSW request handlers from your OpenAPI spec so you can mock the API in tests and during local development.
- Downloads622.2K/ monthnpm, last 30 days
- GitHub stars14kubb-labs/plugins
- Unpacked size273.6kBv6.2.6 on npm
- Latest release4h agov6.2.6 · Nov 23, 2026
The MSW plugin generates a typed MSW request handler for each operation in your OpenAPI spec. Each handler returns the data you pass or Faker mock data.
Installation
kubb add plugin-mswbun add -d @kubb/plugin-mswpnpm add -D @kubb/plugin-mswnpm install --save-dev @kubb/plugin-mswyarn add -D @kubb/plugin-mswkubb add installs the version the Kubb registry pins and adds pluginMsw() to kubb.config.ts. It needs a kubb.config.ts, so run kubb init first in a new project.
Setup
- Add
@kubb/plugin-tsfor the request and response types. - Add
@kubb/plugin-fakerand install@faker-js/fakerv10 when you setparser: 'faker'. - Install
mswv3 in the app that uses the generated code.
Options worth knowing
| Option | Default | What it does |
|---|---|---|
parser | 'data' | Returns the data you pass, or Faker data for operations with a success response schema. |
handlers | false | Writes a handlers.ts that exports every handler and createHandlers({ baseURL }). |
baseURL | None | Prepends a host to the path each handler matches. |
Example
This config generates one handler per operation and a handlers.ts that exports them all. For GET /pets/{petId}, the plugin writes showPetByIdHandler.ts:
import { defineConfig } from 'kubb/config'
import { pluginTs } from '@kubb/plugin-ts'
import { pluginMsw } from '@kubb/plugin-msw'
export default defineConfig({
input: './petStore.yaml',
output: { path: './src/gen' },
plugins: [
pluginTs(),
pluginMsw({ output: { path: 'handlers', mode: 'directory' }, handlers: true }),
],
})import type { ShowPetByIdResponse } from '../types/ShowPetById'
import { http, HttpResponse } from 'msw/http'
export function showPetByIdHandlerResponse200(data?: ShowPetByIdResponse) {
return new HttpResponse<string>(JSON.stringify(data), {
status: 200,
headers: {
'Content-Type': 'application/json',
},
})
}
export function showPetByIdHandler(
data?: ShowPetByIdResponse | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Response | Promise<Response>),
options?: { baseURL?: string },
) {
return http.get(`${options?.baseURL ?? ''}/pets/:petId`, function handler(info) {
if (typeof data === 'function') return data(info)
return showPetByIdHandlerResponse200(data)
})
}Next, register the handlers in tests or the browser.
Dependencies
Extensions that must be in the same config as MSW.
Optional dependencies
Extensions MSW works with when they are in the config.
