Overview

OpenAPI generation and interactive API docs for Vercube

The Schema module (@vercube/schema) turns your route metadata and Zod validation schemas into an OpenAPI 3 document at runtime. It also serves a Scalar API Reference UI so you can browse and try your API without extra tooling.

Define validation once with @Body / @QueryParams, annotate routes with @Schema, and get:

  • OpenAPI JSON at GET /_schema/
  • Scalar docs at GET /_schema/docs (enabled by default)

Both are off in production unless you turn them on, see Exposure and access.

Installation

$ pnpm add @vercube/schema

The package re-exports z with OpenAPI helpers from @asteasolutions/zod-to-openapi. Import z from @vercube/schema (not only from zod) when you want .openapi() metadata on your schemas.

Quick Start

Register the plugin

src/Boot/Setup.ts
import { createApp } from '@vercube/core';
import { SchemaPlugin } from '@vercube/schema';

export async function setup(app: App) {
  app.addPlugin(SchemaPlugin);
}

Or from vercube.config.ts with a class plugin:

vercube.config.ts
import { defineConfig, withPluginOptions } from '@vercube/core';
import { SchemaPlugin } from '@vercube/schema';

export default defineConfig({
  plugins: [SchemaPlugin],
});

Annotate a route

Use @Schema on controller methods. The decorator registers the route in the OpenAPI registry. Request body and query schemas are picked up automatically when you use validationSchema on @Body, @QueryParams, @QueryParam and @Param (see Decorators).

src/controllers/UserController.ts
import { Body, Controller, Post, QueryParams } from '@vercube/core';
import { Schema, z } from '@vercube/schema';

const CreateUserSchema = z.object({
  name: z.string(),
  email: z.string().email(),
});

const ListUsersQuerySchema = z.object({
  page: z.coerce.number().optional(),
});

@Controller('/users')
export class UserController {
  @Post('/')
  @Schema({
    summary: 'Create user',
    responses: {
      201: {
        description: 'Created user',
        content: {
          'application/json': {
            schema: z.object({ id: z.string(), name: z.string() }),
          },
        },
      },
    },
  })
  create(
    @Body({ validationSchema: CreateUserSchema }) body: z.infer<
      typeof CreateUserSchema
    >,
    @QueryParams({ validationSchema: ListUsersQuerySchema }) _query: z.infer<
      typeof ListUsersQuerySchema
    >,
  ) {
    return { id: '1', ...body };
  }
}

Open the docs

With the dev server running:

URLContent
/_schema/OpenAPI 3.0 JSON
/_schema/docsScalar API Reference (HTML)
The playground app already registers SchemaPlugin - try http://localhost:3000/_schema/docs after pnpm dev in playground/.

Zod and OpenAPI metadata

Use .openapi() on Zod types for richer docs (examples, component names):

const UserSchema = z
  .object({
    id: z.string().openapi({ example: 'usr_123' }),
    name: z.string().openapi({ example: 'Jane Doe' }),
  })
  .openapi('User');

Reference named components in @Schema responses:

@Schema({
  responses: {
    200: {
      description: 'User',
      content: {
        'application/json': { schema: UserSchema },
      },
    },
  },
})

Plugin options

SchemaPlugin accepts optional SchemaPluginOptions:

import { SchemaPlugin } from '@vercube/schema';

app.addPlugin(SchemaPlugin, {
  scalar: {
    pageTitle: 'My API',
    config: { theme: 'purple' },
  },
});

// Disable Scalar UI (OpenAPI JSON remains at /_schema/):
app.addPlugin(SchemaPlugin, { scalar: false });

Document metadata and security

document sets the top-level fields of the OpenAPI document (info, servers, security, tags, externalDocs). Missing info fields default to API / 1.0.0. components adds reusable components, such as the security schemes referenced from security:

app.addPlugin(SchemaPlugin, {
  document: {
    info: { title: 'Community API', version: '2.3.0' },
    servers: [{ url: 'https://api.example.com/v1' }],
    security: [{ bearerAuth: [] }], // applies to every route
  },
  components: {
    securitySchemes: {
      bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' },
    },
  },
});

Routes guarded by @Auth() (on the controller, the method, or registered for the whole application) are documented with a security requirement of their own: the security plugin option, else document.security, else any one of the declared securitySchemes. When document.security is set, every route without @Auth() is documented as public (security: []). @Schema({ security }) overrides both.

app.addPlugin(SchemaPlugin, {
  components: {
    securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer' } },
  },
  security: [{ bearerAuth: [] }], // what @Auth() means in the document
});

Exposure and access

The document lists every route, parameter, body shape and security scheme of your API, so the endpoints are not served when the application runs with production: true. The document is still generated and stays available to introspection.

OptionTypeDefaultDescription
enabledbooleantrue, false in productionServe <path>/ and <path>/docs
pathstring'/_schema'Where the document is served, the Scalar UI is at <path>/docs
tokenstring-Access token both endpoints require

To publish the reference from a production deployment behind a token:

app.addPlugin(SchemaPlugin, {
  enabled: true,
  path: '/internal/openapi',
  token: process.env.SCHEMA_TOKEN,
});

Send the token as the x-schema-token header:

curl -H "x-schema-token: $SCHEMA_TOKEN" https://api.example.com/internal/openapi/

In a browser, open /internal/openapi/docs?token=.... With a token set, the page embeds the document instead of fetching it, so the UI works without sending the header. The JSON endpoint ignores ?token= to keep the token out of access logs.

Application-wide middlewares still run in front of both endpoints, so an existing global auth middleware guards them too. When the endpoints are served in production without a token, the plugin logs a warning at boot.

Documenting every route

includeAllRoutes: true documents every routed method, not only those with @Schema. They get what can be derived from the route: path, parameters, body, responses, operationId and tags. The schema endpoints themselves and infrastructure controllers such as devtools stay out.

app.addPlugin(SchemaPlugin, { includeAllRoutes: true });

See Scalar integration for all Scalar-related options.

Relationship to validation

Schema generation is additive to Validation. Validation runs on every request via middleware; @Schema only affects documentation and the generated OpenAPI spec. Use the same Zod schemas for both when possible so docs stay in sync with runtime behavior.