Skip to content
Introduction

Architecture

Follow an API spec through Kubb's pipeline, from adapter to AST, plugins, parsers, and storage, and see which extension point changes each stage.

Kubb runs your spec through one pipeline, and you can replace or extend each stage.

01 · CONFIGkubb.config.ts02 · SETUPadapter → AST03 · BUILDplugins04 · FILE PROCESSORparsers → storage

You declare the input spec, the output folder, an adapter, and the plugins to run. defineConfig pre-wires the OpenAPI adapter and the default parsers.

inputoutputadapterplugins
StageJobOutput
AdapterReads the spec and resolves its referencesAn InputNode
ASTDescribes schemas and operations without naming a spec format or a librarySchema and operation nodes
PluginsRun generators that decide which files and declarations to emitFileNodes
ParsersTurn each file's nodes into source textSource code
StorageWrites the filesFiles on disk or in memory

From one operation to generated files

Take GET /pet/{petId} (getPetById), whose response refers to a Pet schema:

  1. The adapter resolves the $ref into an operation node and a Pet schema node.
  2. plugin-ts emits the Pet and GetPetById types, and plugin-axios emits a getPetById function that imports them.
  3. A parser prints each file, and storage writes it.

Generate your first client builds this example.

Adapters

An adapter handles everything specific to the input format: references, nullability, discriminators, and formats. The default is the OpenAPI adapter. A custom adapter converts another format into the same AST, so every plugin works with it.

adapter.parse(spec) → InputNode
OpenAPI 3.0
Pet:  properties:    owner:      $ref: '#/components/schemas/User'    tag:      type: string      nullable: true    createdAt:      type: string      format: date-time
InputNode
{  kind: 'Schema', name: 'Pet',  properties: {    owner: {      kind: 'ref', name: 'User' },    tag: {      kind: 'union',      of: ['string', 'null'] },    createdAt: {      type: 'datetime' },  },}

$ref resolves to a ref node by name. Plugins never see the JSON pointer.

AST

The AST is the model the adapter and the plugins share, so no plugin resolves references itself. An InputNode holds the reusable schemas and the operations, and operations link parameters, request bodies, and responses to schema nodes.

InputNodethe parsed specschemasSchemaNode[]operationsOperationNode[]parametersParameterNode[]requestBodyRequestBodyNoderesponsesResponseNode[]contentContentNodeschema is a ref, not a copy
An InputNode holds everything the adapter read: the reusable schemas and the operations.

Every node has a kind, and schema nodes also have a type. See AST and node builders.

Plugins

Each plugin owns one output, such as types, a client, or your own files. defineExtension({ kind: 'plugin' }) returns the factory you call in kubb.config.ts. Its setup runs once and registers generators, a resolver, and macros.

InputNodemacrosrewrite nodesgeneratorswalk the ASTrendererJSX → FileNodeFileNode[]optionsresolverPLUGIN · @kubb/plugin-tsINPUTOUTPUTwhat and how to generatenames files & imports
An InputNode arrives from the adapter: the schemas and operations of the spec.

Generators

A generator turns AST nodes into files.

HandlerKubb calls it
schemaOnce per schema node
operationOnce per operation node
operationsOnce per plugin, with every operation node its filters keep

A handler returns FileNodes or elements for a renderer. See Generators.

Resolvers

A resolver decides identifiers, file names, and paths. A plugin that builds on another reads its resolver, so the Axios client still imports the right names after you rename the types. See Resolvers.

Macros and printers

A macro rewrites AST nodes before the generators see them, per plugin, so a change reaches every generator of that plugin and no other. A printer turns a schema node into code for one target, such as a TypeScript type or a Zod expression. See Macros and Printers.

Renderers

A renderer turns the elements a generator returns into FileNodes. jsxRenderer from kubb/jsx renders JSX without React. Set it per generator with renderer. See JSX renderer.

Lifecycle

kubb:lifecyclekubb:lifecycle:start
kubb:lifecyclekubb:generationsetupbuildformatlinthooksplugin-tsfilesplugin-zodschemaoperationoperationsplugin:setup ×2plugins:endkubb:info · success · warn · error · diagnostic fire at any point
Pause the playhead to read a hook. On the wide trace, hover or focus a span to jump to the hook that opens it.
  1. The adapter parses the spec.
  2. Each plugin's setup and kubb:plugin:setup run once, in plugin order.
  3. Kubb walks the AST once, schemas first. Each node goes to every plugin, through its macros and include, exclude, and override filters.
  4. Each plugin's operations handler runs, then kubb:plugin:end fires.
  5. After kubb:plugins:end, Kubb writes all files through the parsers and storage.
  6. Format, lint, and postGenerate run when the config sets them.

Lifecycle hooks lists every hook.

Dependencies and ordering

Kubb orders the plugins before setup:

foundplugins leftnoneSort by enforce:pre, normal, postFirst plugin whosedependencies are placedPlace it nextFail: dependency cycle

Dependencies win over enforce, and ties keep their order in plugins. With plugins: [pluginAxios(), pluginTs()], plugin-ts comes first because plugin-axios depends on it. plugin-barrel, which defineConfig adds, sets enforce: 'post', so it runs last and sees every file the others emitted.

Parsers

Kubb sends each FileNode to the parser that claims its extension. Without a parsers option, defineConfig adds parserTs (.ts, .js), parserTsx (.tsx, .jsx), and parserMd (.md, .markdown). The TypeScript parser prints a file's banner, imports, and source nodes:

parserTs.parse(file) → source
FileNode
{  kind: 'File',  path: 'src/gen/types/Pet.ts',  banner: '/* eslint-disable */',  imports: [{    name: ['Status'],    path: './Status',    isTypeOnly: true,  }],  sources: [{ nodes: [{    kind: 'TypeAlias', name: 'Pet',    members: { id: 'number',               status: 'Status' },  }] }],}
src/gen/types/Pet.ts
/* eslint-disable */import type { Status } from './Status' export type Pet = {  id: number  status: Status}

banner prints first. A footer would print last.

To write one, see Parsers.

Storage

Storage decides where files go, so the same build writes to disk from the CLI or to memory in a test. Kubb skips files whose content has not changed.

DriverWrites to
fsStorage()Disk. The default.
memoryStorage()A Map in memory
Your ownAny backend that implements the Storage interface

Choose an extension

If an existing plugin generates the output you need, use it. Otherwise, build on kubb/kit, which ships with kubb.

The input formatAdd a new outputAn existing outputWhat a schema meansCode for one schema typeFile names or pathsFile syntaxWhere files goWhat do you need tochange?AdapterPlugin with generatorsWhich part?MacroPrinterResolverParserStorage
ExtensionExampleStart with
AdapterRead a format other than OpenAPIAdapters
PluginGenerate a new kind of fileCreate a plugin
MacroTreat every integer as a string in one pluginMacros
PrinterPrint date schemas as the TypeScript Date typePrinters
ResolverMove model files into a folderResolvers
ParserEmit a new file typeParsers
StorageWrite to a remote storeStorage