OrvalOrval

Valibot

Generate Valibot schemas from OpenAPI

Generate Valibot schemas from your OpenAPI specification for runtime validation. The generated code needs valibot 1.0 or newer:

npm install valibot

Choosing a Mode

client: 'valibot'schemas: { type: 'valibot' }
Use it toParse and validate data yourselfMake a generated HTTP client validate its responses
GeneratesA schema for the params, query, headers, body and response of each operationA schema for each model, and for each operation's query params and headers, plus its request body and responses when they are not a $ref
Type namesNone, except on recursive schemas with generateReusableSchemas: Pet is the output, PetInput the inputEvery schema: Pet is the input, PetOutput the output

To use both, generate them in separate outputs. See Combining with HTTP Clients.

Configuration

Set the client option to valibot:

orval.config.ts
import { defineConfig } from 'orval';

export default defineConfig({
  petstore: {
    output: {
      client: 'valibot',
      mode: 'single',
      target: './src/api/schemas.ts',
    },
    input: {
      target: './petstore.yaml',
    },
  },
});

Generated Output

Orval generates a Valibot schema for the params, query, headers, body and response of each operation. The body and response schemas come from JSON, multipart/form-data or application/x-www-form-urlencoded content, and the response schema from the first of 200, 2XX/2xx and the other 2xx responses (except 204 and 205) that has such content. Other media types, such as text/plain, get no schema:

import * as v from 'valibot';

export const CreatePetsBody = v.object({
  id: v.pipe(v.number(), v.integer()),
  name: v.string(),
  tag: v.optional(v.string()),
});

Options

Options live under override.valibot:

  • strict - per location (param, query, header, body, response), emit v.strictObject instead of v.object. All false by default.
  • generate - per location, choose which schemas are generated. All true by default.
  • exactOptional - use v.exactOptional for optional properties, for projects with exactOptionalPropertyTypes. false by default. Can also be set per operation or tag.
  • generateReusableSchemas - emit each component schema once and reference it, instead of inlining every $ref. false by default. See Reusable Schemas.

Reusable Schemas

By default every $ref is inlined, which makes the output large for a spec with many shared components. With generateReusableSchemas, each #/components/schemas/* entry becomes one exported constant:

orval.config.ts
export default defineConfig({
  petstore: {
    output: {
      client: 'valibot',
      target: './src/api/schemas.ts',
      override: { valibot: { generateReusableSchemas: true } },
    },
    input: { target: './petstore.yaml' },
  },
});
export type Pet = {
  name: string;
  friends?: Pet[] | undefined;
};

export type PetInput = {
  name: string;
  friends?: PetInput[] | undefined;
};

export const Pet = v.object({
  name: v.string(),
  friends: v.optional(
    v.array(v.lazy((): v.GenericSchema<PetInput, Pet> => Pet)),
  ),
});

export const ListPetsResponse = v.array(Pet);

The constants go next to the operations: into the target in single mode, into a *.schemas.ts file in the other modes. A reference that closes a cycle reads through v.lazy.

Each constant on a cycle also gets two exported types: Pet for its output and PetInput for its input. The v.lazy getter uses them, so the recursive field is typed Pet[] instead of unknown. When another schema already has the name PetInput, the input type becomes PetInput2. A field converted by an inline formatType decode, such as (value) => dayjs(value), is typed unknown in these types. Name a function, such as 'dayjs', to type it with that function's return type.

Limitations

  • With client: 'valibot', generateReusableSchemas and output.schemas can't be set together: generation fails with an error. To write the schemas to their own module, set schemas.type to valibot with an HTTP client.
  • A $ref is still inlined where a constant would validate differently, such as form bodies, readOnly and writeOnly properties, and some allOf, oneOf and anyOf members.
  • A constant keeps all its properties and is strict only when every location is. A location with a different strict, or an operation override of exactOptional, inlines its schemas.
  • A oneOf or anyOf with a discriminator becomes v.union when an option is a reference.
  • A component named Date or RegExp gets a Schema suffix. Two components with the same name stop generation with an error.

Checking Against the Models

Models and schemas come from separate generators, so they can drift apart without anyone noticing. When a project generates TypeScript models in another configuration, the shared override.modelTypeChecks option, which also works with Zod, makes the schemas file assert that each component schema outputs what its model declares:

orval.config.ts
export default defineConfig({
  api: {
    output: {
      client: 'fetch',
      target: './src/api/endpoints.ts',
      schemas: './src/api/model',
    },
    input: { target: './petstore.yaml' },
  },
  validation: {
    output: {
      client: 'valibot',
      target: './src/validation/schemas.ts',
      override: {
        valibot: { generateReusableSchemas: true },
        modelTypeChecks: { models: './src/api/model' },
      },
    },
    input: { target: './petstore.yaml' },
  },
});

models is the directory the other configuration writes its models to, like its output.schemas. A relative path starts at the workspace of this configuration, which can differ from that of the other one, and an absolute path is used as it is. The schemas file imports it and gets a type-only block. Nothing changes at runtime:

import type * as Models from '../api/model';

type Assert<T extends true> = T;
type Extends<A, B> = [A] extends [B] ? true : false;
type SchemaModelTypeChecks = {
  Pet: [
    Assert<Extends<v.InferOutput<typeof Pet>, Models.Pet>>,
    Assert<Extends<Models.Pet, v.InferOutput<typeof Pet>>>,
  ];
};
declare const schemaModelTypeChecks: SchemaModelTypeChecks;

The type is not exported, so a barrel that re-exports several of these files does not clash on it. The ambient declare const reads it, so noUnusedLocals stays quiet, and it emits no code.

When a schema and its model are not assignable both ways, your own tsc run fails on the assertion of that component, with Type 'false' does not satisfy the constraint 'true'.

  • Both configurations must use the same naming options, such as override.components.schemas, so a model has the name of its schema.
  • Assignability in both directions does not catch an optional property that only one side declares, nor a type that is any on either side. Required properties, nullability, readonly arrays, enums, unions and nested or recursive types are caught.
  • The check imports the index.ts of the models and needs it to export every component by name. Keep indexFiles on, which is the default, in the configuration that writes the models.
  • An option such as formatType or useDates that maps a type in the schemas must map it in the models too. Set useBigInt and useReadonlyArrays in both configurations, so the checks skip the components they change.
  • With exactOptionalPropertyTypes in your tsconfig, the models type an optional property as a?: T, so set exactOptional: true in override.valibot, or every optional property fails the check. Orval warns at generation when the tsconfig it reads sets the flag and exactOptional is off.
  • modelTypeChecks rejects useBrandedTypes, useNullForOptional, enumGenerationType: 'enum' and namingConvention.properties with an error, because they shape the models in ways a schema output cannot match. A TypeScript enum is not assignable from the string literals a schema outputs, so use 'const' or 'union' in the configuration that writes the models too.

Skipped components

Orval types some schemas more loosely than their models on purpose, so no schema could match the model there. A component that holds one has no assertion. A comment in the block says why, so the file still compiles:

type SchemaModelTypeChecks = {
  Pet: [
    Assert<Extends<v.InferOutput<typeof Pet>, Models.Pet>>,
    Assert<Extends<Models.Pet, v.InferOutput<typeof Pet>>>,
  ];
  // Point: skipped, prefixItems is validated as an array of unknown
};
declare const schemaModelTypeChecks: SchemaModelTypeChecks;

A component that references a skipped one is skipped too, because its output type holds the other's. The constructs are:

  • prefixItems (a tuple) is validated as an array of unknown.
  • A circular reference that cannot be kept is validated as unknown.
  • A binary string, such as format: binary, is validated as File, and the model types it as Blob.
  • A default on an optional property makes the key required in the output only. For Valibot, this includes a property that references a schema with a default.
  • additionalProperties next to properties is typed as unknown by the model, and the schema checks it.
  • An enum allOf member next to the properties of the same schema is an alternative in the model and is intersected in the schema.
  • A schema without a type, such as {} or one with only a description, is validated as unknown, and the model types it as {}.
  • A schema without a type that only describes an object, with additionalProperties, patternProperties or an empty properties, is validated as unknown at any depth, in a property or an allOf member too, and the model types it as an object.
  • A const that is an object or an array is not validated, and an enum with such a member is validated as unknown.
  • A required key that no property declares, such as required: [id] without properties, is validated as unknown, and the model leaves it out.
  • A key that a oneOf or anyOf schema requires while only its alternatives declare it, such as required: [id] next to an alternative that lists id as optional, is required in each alternative that declares it, and the model leaves each one as it declares it.
  • A oneOf or anyOf alternative that only requires keys, such as { required: [id] }, next to the properties of an object, is validated as an object with those keys, and the model types it as unknown.
  • With useBigInt, a 64-bit integer (format: int64 or uint64) is a bigint in the model and a number in the schema.
  • With useReadonlyArrays, an array is readonly in the model, and the schema output is not.
  • A readOnly beside a reference to an array makes the output readonly, which the model does not.
  • A readOnly array in the items of an array is readonly in the schema, and the model puts readonly on the outer array.
  • A const with null in its type is typed without null by the model.
  • A component whose properties are all a const is written as a constant object by the model, so every key is required. A component with an optional one differs from the schema.
  • A oneOf or anyOf with a null, nullable or enum alternative, next to the properties or allOf of the same schema: the model merges the alternatives and drops the own properties of an enum, and the schema intersects them.

Usage

Parsing Data

import * as v from 'valibot';
import { CreatePetsBody } from './src/api/schemas';

const pet = v.parse(CreatePetsBody, { id: 1, name: 'Buddy', tag: 'dog' });
// => { id: 1, name: "Buddy", tag: "dog" }

Type Inference

import * as v from 'valibot';
import { CreatePetsBody } from './src/api/schemas';

type Pet = v.InferOutput<typeof CreatePetsBody>;

const pet: Pet = { id: 1, name: 'Buddy', tag: 'dog' };

Safe Parsing

import * as v from 'valibot';
import { CreatePetsBody } from './src/api/schemas';

const result = v.safeParse(CreatePetsBody, unknownData);

if (result.success) {
  console.log(result.output);
} else {
  console.error(result.issues);
}

Mapping

  • oneOf and anyOf become v.union, or v.variant when a discriminator is set. allOf becomes v.intersect.
  • Objects strip unknown keys. The strict option emits v.strictObject, and additionalProperties emits v.looseObject or v.record.
  • date and date-time strings are validated as ISO dates, and a date-time needs an offset such as Z. With override.useDates they are converted to Date.
  • Binary fields (format: binary) become v.file(), including file parts in multipart/form-data bodies.
  • readOnly properties are left out of request bodies, and writeOnly properties out of responses. A readOnly array with items gets v.readonly(), so its output is a readonly array, as in the model. suppressReadonlyModifier turns this off for both.
  • A default that does not fit its schema is left out, with a warning.

Limitations

  • A circular $ref is validated as unknown, with a warning, wherever it is inlined. With generateReusableSchemas, component constants validate recursively through v.lazy.
  • prefixItems tuples are validated as unknown[], with a warning.
  • When an item of a readOnly array fails a check, valibot skips the array's own checks, such as maxItems. A v.union around the array, or around an object that contains it, then reports one generic issue instead of the item's issue. A date conversion or formatType decoder has the same effect on a string that fails a check.
  • Every $ref is inlined unless generateReusableSchemas is set, so shared schemas can make the output large. Inlining one schema stops with an error past 250,000 schema nodes.
  • oneOf does not check that exactly one alternative matches.
  • Query and path params are not coerced: a number read from a URL string fails v.number(). Header keys keep the casing of the spec.
  • Inside an allOf intersection, strict objects are emitted as v.object, so extra keys are stripped instead of rejected. An open member (additionalProperties: true) next to an object member is left out, so extra keys are stripped too.

Validating HTTP Client Responses

Set schemas.type to valibot and turn on the client's runtimeValidation. The generated client then validates responses with Valibot schemas instead of Zod.

orval.config.ts
export default defineConfig({
  petstore: {
    output: {
      client: 'fetch',
      target: './src/api/endpoints.ts',
      schemas: { path: './src/api/model', type: 'valibot' },
      override: {
        fetch: { runtimeValidation: true },
      },
    },
    input: { target: './petstore.yaml' },
  },
});

Every schema goes to one module, <schemas.path>/index.valibot.ts, or schemas.path itself when it names a file. There is no index.ts barrel, so here you import from ./src/api/model/index.valibot. Each schema also exports the types X (v.InferInput) and XOutput (v.InferOutput). A schema on a cycle declares both types in full instead, because they cannot be inferred, so its recursive fields keep their types.

  • Validation runs through the runtimeValidation option of override.fetch for fetch and for react-query, vue-query, svelte-query, solid-query, swr, pinia-colada with httpClient: 'fetch', override.angular for angular, and override.query for angular-query. It is off by default.
  • standardSchema is always on, because Valibot schemas have no parse method. Validation errors are therefore StandardSchemaError, not ValiError, so v.isValiError() is false for them. Read error.issues. Async schemas are not supported.
  • Axios clients do not validate.
  • Generated validation is skipped for custom mutators. With includeSchemaInArguments, the custom mutator of fetch or a fetch-backed client receives the schema as schema and validates the response itself through schema['~standard'].validate(). Angular clients do not pass the schema to a mutator.
  • useDates makes the schemas turn date strings into Date, so XOutput has Date where X has string. useDatesTransform turns on useDates and nothing more: the client adds no date deserializer.

The following fail with a configuration error: schemas.mode: 'split', schemas.routes, schemas.splitByTags, mock generators (for MSW, add a second output with TypeScript models), operationSchemas, factoryMethods, splitByContentType, standardSchema: false, override.formatType, override.useBigInt, override.namingConvention.properties, Angular runtimeValidation.requestBodies with useDates, and the clients zod, effect, valibot, hono and mcp.

Known limits:

  • With the fetch clients and the default forceSuccessResponse: false, a JSON error response is validated against the success schema, whatever its status. A 404 body that does not fit the schema throws a StandardSchemaError, and one that fits passes. Zod does the same. With forceSuccessResponse: true, and in the Angular clients, an error status is not validated.
  • Requests and responses share a component schema, so a required writeOnly property is optional in it, and a required readOnly property is still required in request body types.
  • format: binary maps to v.file() also in JSON, so a JSON response with such a property fails validation. A binary value is typed File, not Blob.

See the Valibot with fetch sample on GitHub. It has one output that validates in the generated client, and one with a mutator that validates through ~standard.

Combining with HTTP Clients

The valibot client generates schemas only. To have an HTTP client validate its responses, use schemas.type instead.

To use the valibot client next to an HTTP client, for example to check a request body before sending it, generate each in its own output. Give each output its own target, or the Valibot output overwrites the client files. In tags and tags-split mode the file name of a target is ignored and only its directory counts: with the default file extension, http.ts and validation.ts in one directory both write pets.ts for the tag pets. Use separate directories there, or set fileExtension: '.valibot.ts' on the Valibot output so the two can share one. The same setting lets split mode share a directory target such as ./src/api. A shared file target can still collide: ./src/api/endpoints.valibot.ts makes both outputs write endpoints.valibot.ts.

On this page