Skip to content
Plugin
MSW logo
plugins: [pluginMsw()]
Officialv6.2.6kubb >=5.19.0node >=22.22

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.

kubb add plugin-msw
mswmock-service-workerapi-mockingmockstestingcodegenopenapi

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-msw

kubb 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-ts for the request and response types.
  • Add @kubb/plugin-faker and install @faker-js/faker v10 when you set parser: 'faker'.
  • Install msw v3 in the app that uses the generated code.

Options worth knowing

OptionDefaultWhat it does
parser'data'Returns the data you pass, or Faker data for operations with a success response schema.
handlersfalseWrites a handlers.ts that exports every handler and createHandlers({ baseURL }).
baseURLNonePrepends 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 }),
  ],
})

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.