OrvalOrval

Zod

Generate Zod schemas from OpenAPI

Generate Zod schemas from your OpenAPI specification for runtime validation.

Configuration

Set the client option to zod:

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

export default defineConfig({
  petstore: {
    output: {
      client: 'zod',
      mode: 'single',
      target: './src/api/schemas',
      override: {
        zod: {
          // Prefer Mini for more tree-shakeable generated schemas.
          variant: 'mini',
          version: 4,
        },
      },
    },
    input: {
      target: './petstore.yaml',
    },
  },
});

Generated Output

Orval generates a Zod schema for each model in your OpenAPI specification:

export const CreatePetsBody = /*#__PURE__*/ zod.object({
  id: /*#__PURE__*/ zod.number(),
  name: /*#__PURE__*/ zod.string(),
  tag: /*#__PURE__*/ zod.optional(/*#__PURE__*/ zod.string()),
});

Tree Shaking

Prefer variant: 'mini' when startup time, memory usage, or bundle size matter. Zod Mini uses top-level helpers, so generated validators can be dropped more reliably when their exports are unused:

// Regular Zod
export const User = zod.object({
  email: zod.email().min(5).max(255),
});

// Zod Mini
export const User = /*#__PURE__*/ zod.object({
  email: /*#__PURE__*/ zod
    .email()
    .check(/*#__PURE__*/ zod.minLength(5))
    .check(/*#__PURE__*/ zod.maxLength(255)),
});

When User is unused, a bundled regular Zod output can still keep the schema initializer as top-level work even if nothing uses it:

// possible bundled regular Zod output (no export const User, but the zod call is still there)
object({
  email: email().min(userEmailMin).max(userEmailMax),
});

With Zod Mini + pure annotations, the unused schema can disappear entirely:

// possible bundled Zod Mini output
// no User schema code emitted at all

In large generated clients this can remove unused schema initializers from the final bundle. In real builds this can mean hundreds of kilobytes less generated validation code loaded at startup.

Array response items

Inline array response items can use OpenAPI compositions such as allOf, oneOf, or anyOf. Orval generates a schema for the item type, for example:

export const ListAllOf200Item = zod.object({
  id: zod.int().optional(),
}).and(
  zod.object({
    extra: zod.string().optional(),
  }),
);

The generated client can then use ListAllOf200Item[] for the response. When an array item is a component $ref, the component schema writer owns that schema and the operation does not generate a duplicate item schema.

Zod version

Orval uses Zod 4 as its output baseline (z.strictObject, z.looseObject, z.iso.datetime(), .meta(), …), while projects still on Zod 3 are fully supported. The emitted syntax follows whichever zod major your project resolves.

With the default ('auto'), Orval infers the target from the zod version resolved in your project's package.json. When no zod package can be detected — for example in a fresh or partially-installed workspace — it falls back to Zod 4.

To make generation deterministic, pin the target with override.zod.version:

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

export default defineConfig({
  petstore: {
    output: {
      client: 'zod',
      target: './src/api/schemas',
      override: {
        zod: {
          variant: 'mini',
          version: 4, // 3 | 4 | 'auto'
        },
      },
    },
    input: {
      target: './petstore.yaml',
    },
  },
});
ValueOutput
4Always emit Zod 4 syntax, regardless of the installed zod version.
3Always emit Zod 3-compatible syntax, regardless of the installed zod version.
'auto'(default) Infer from the resolved zod version; fall back to Zod 4 when none is detected.

Pinning the version keeps output stable: the same spec produces the same schemas on every machine and in CI, independent of which zod version happens to be installed.

The override only selects Zod 3 or Zod 4 syntax. Output that depends on a specific Zod 4 release, such as zod.xor for oneOf with generateXor (see below), still follows the zod version: the installed one, or the lower bound of the declared range when zod is not installed yet. Declare a range whose lower bound already has the feature (^4.2.0 for zod.xor) for fully reproducible output.

oneOf and anyOf

Both oneOf and anyOf are emitted as zod.union([...]) by default. oneOf means exactly one branch must match, so set generateXor to emit it as zod.xor([...]) on Zod 4.2+. It is opt-in because non-strict object branches strip unknown keys, so a payload for a subtype also matches its supertype (oneOf: [Pet, Dog] where Dog extends Pet) and zod.xor rejects it. anyOf stays a zod.union([...]), and so do type arrays (type: ['integer', 'number']), whose members can overlap, and mixed-type enums, which mean "equals one of the values". Even with generateXor, oneOf stays zod.union([...]):

  • on Zod 3 and Zod 4.0/4.1, which have no xor, or when no zod version can be detected;
  • when a branch is coerced, since coercion can make branches overlap ("42" passes both zod.string() and zod.coerce.number());
  • when a branch renders looser than the spec ({}, a required-only branch, or a keyword Orval drops such as not), since two loose branches would both match;
  • when it has a discriminator, which is emitted as zod.discriminatedUnion(...) instead when generateDiscriminatedUnion is enabled.

Zod Mini

Set override.zod.variant to 'mini' to generate schemas against Zod Mini:

orval.config.ts
export default defineConfig({
  petstore: {
    output: {
      client: 'zod',
      override: {
        zod: {
          variant: 'mini',
          version: 4,
        },
      },
    },
  },
});

Mini output imports from zod/mini and uses Zod Mini's functional/check-based API. It requires Zod 4; version: 3 or version: 'auto' resolving to Zod 3 is rejected.

Prefer Zod Mini when generated schemas are bundled into frontend apps, Cloudflare Workers, or other startup-sensitive runtimes where tree-shaking and bundle size matter. Use regular Zod when those constraints are not important; it has the more familiar chainable API and better autocomplete ergonomics.

One behavior difference: Zod Mini does not load the English locale by default. Configure it once if you want regular Zod's default English messages:

import * as zod from 'zod/mini';

zod.config(zod.locales.en());

Unsupported Schemas

Some schemas are validated more loosely than the spec says. By default Orval generates them without a message. Set override.zod.unsupported to 'error' to fail the generation instead. The error names the schema, such as getPetResponse > owner > tags, and says how to turn the check off.

orval.config.ts
export default defineConfig({
  petstore: {
    output: {
      client: 'zod',
      target: './src/api/endpoints.ts',
      override: { zod: { unsupported: 'error' } },
    },
  },
});

These cases fail in 'error' mode. When a setting fixes a case, the error names it. additionalProperties: false without strict does not fail.

  • Keywords with no Zod counterpart: not (except an empty one, or one that only forbids keys in a oneOf/anyOf branch next to sibling properties), if/then/else, patternProperties, propertyNames, dependentSchemas, dependencies, unevaluatedProperties, unevaluatedItems, contains, minContains, maxContains, uniqueItems, minProperties, maxProperties, additionalItems and contentSchema. dependentRequired fails where it cannot be rendered: on an object without properties, or next to a composition.
  • Constraints on a schema with no type (minimum, minLength, pattern, items, ...), an object or array const, and items given as a list.
  • A oneOf that renders as a plain union, unless its alternatives have distinct types, literals or discriminator values. Without generateXor the error says to turn it on. A coerced alternative also renders the oneOf as a plain union.
  • More than one composition keyword on the same schema, as only the first of allOf, oneOf and anyOf is rendered.
  • An allOf of objects merged into one object, with strict or in a discriminated union, that declares the same property, or additionalProperties, differently: the merge keeps one definition. A literal or enum that narrows an earlier type or enum is accepted.
  • An array at the root of a body or response with prefixItems, null, enum, const, a composition or a format: only its items and bounds are rendered.
  • An unresolvable $ref or $dynamicRef, and a circular $ref that is inlined, since all are validated as unknown. Without generateReusableSchemas the error says to turn it on.
  • A format zod does not check, such as format: phone, unless formatType maps it. The checked formats are date, time, time-local, date-time, date-time-local, email, uri, hostname, uuid, ipv4, ipv6 and binary, plus the number formats int32, int64, float and double through the number type. A contentEncoding, such as base64, is not checked either.

Scoping options per operation or tag

Most override.zod settings can be applied to part of your API instead of globally, via override.operations[operationId].zod (a single operation) or override.tags[tagName].zod (every operation sharing a tag):

orval.config.ts
export default defineConfig({
  petstore: {
    output: {
      client: 'zod',
      override: {
        zod: {
          variant: 'mini',
          version: 4,
          strict: { response: true }, // applies everywhere
        },
        operations: {
          listPets: {
            zod: {
              coerce: { query: ['number'] }, // only this operation
            },
          },
        },
        tags: {
          admin: {
            zod: {
              strict: { body: true }, // every operation tagged "admin"
            },
          },
        },
      },
    },
  },
});

Per-operation and per-tag overrides accept the settings that apply to an individual schema: strict, generate, coerce, preprocess, params, useBrandedTypes, and generateCompanionTypes.

Output-wide settings — variant, version, dateTimeOptions, timeOptions, generateEachHttpStatus, generateReusableSchemas, generateMeta, generateDiscriminatedUnion, generateXor, exactOptional, and unsupported — only make sense for the whole output and must stay on override.zod. If you place one on an operation or tag it is ignored — the value from override.zod still applies — and Orval prints a build warning:

⚠️ override.operations.listPets.zod only supports strict, generate, coerce, preprocess, params, useBrandedTypes, and generateCompanionTypes. Ignoring unsupported field: zod.version.

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 Valibot, makes the schemas file assert that each component schema outputs what its model declares. It needs generateReusableSchemas and works when the schemas are written next to the operations, so without output.schemas:

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: 'zod',
      target: './src/validation/schemas.ts',
      override: {
        zod: { 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<zod.output<typeof Pet>, Models.Pet>>,
    Assert<Extends<Models.Pet, zod.output<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'. The check reads zod.output, which Zod 3, Zod 4 and Zod Mini all have.

  • 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, enums, unions and nested types are caught.
  • A recursive component is checked against the type its constant is annotated with, which Orval writes from the model generator, so only a drift in how the two handle the component itself shows up there.
  • 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.zod, or every optional property fails the check. It needs Zod 4.3 or later, since .exactOptional() does not exist in Zod 3 or in Zod 4.0 to 4.2. Orval warns at generation when the tsconfig it reads sets the flag and exactOptional is off, and when the Zod version it detects is below 4.3, where no setting of exactOptional satisfies it: upgrade Zod, or set exactOptional: false and turn the flag off.
  • modelTypeChecks rejects useBrandedTypes, useNullForOptional and enumGenerationType: 'enum' with an error, because they shape the models in ways a Zod 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. namingConvention.properties is accepted, since Zod renames the keys of its output as the models do.

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<zod.output<typeof Pet>, Models.Pet>>,
    Assert<Extends<Models.Pet, zod.output<typeof Pet>>>,
  ];
  // Labels: skipped, a readOnly array is readonly in the model, which the schema output is not
};
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:

  • A readOnly array with items is readonly T[] in the model, and a Zod schema outputs T[].
  • A default on an optional property makes the key required in the output only.
  • additionalProperties next to properties is typed as unknown by the model, and the schema checks it.
  • For an object with additionalProperties: false and a finite set of optional properties, minProperties: 1 requires one of those properties in the model. The generated validator still accepts {}.
  • A schema without a type, such as {} or one with only a description, is validated as unknown, and the model types it as {}.
  • A component without a type that only has patternProperties, an empty properties or additionalProperties: false is validated as unknown, and the model types it as an object. Zod keeps a record for additionalProperties with a schema or true, and a property or a member of that kind is untyped in the model too.
  • A const that is an object or an array is not validated.
  • 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.
  • An allOf with an enum member, next to properties of the same schema: the model makes the member and the own properties alternatives, and the schema intersects them.
  • A $ref to anything but a whole component schema, such as #/paths/... or #/components/responses/..., is validated as unknown.
  • 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 tuple (prefixItems) with items and a maxItems that is no more than the number of its prefix items keeps its rest items in the model, and the schema leaves them out.
  • A circular reference that runs through a tuple (prefixItems) is inlined one level by Zod and validated as unknown after that, so a component on such a cycle has no assertion.
  • A type with null that is not an object type ('null' or ['null', 'string']) next to allOf, oneOf or anyOf: Zod validates the composition and drops the null. A ['object', 'null'] type keeps it and has an assertion.
  • With Zod 3, a required property without a type ({}, true or a reference to it, one with only a description or a not, an object shape such as additionalProperties: false, or a oneOf with such a member) is optional in the output, and the model requires it, also when the property and the required list sit in different allOf members. Zod 4 keeps the key required.
  • With Zod 3, an enum with no primitive member (empty, or with objects and arrays only) is validated as never.
  • A const next to a string format (email, uuid, ...) is validated as the format, not as the literal, and a binary string (format: binary, or contentMediaType: application/octet-stream without a contentEncoding) with a const is validated as a file.
  • items: false without prefixItems is unknown[] in the model and never[] in the schema.
  • A not of an empty schema (not: {}) is validated as never, and the model types it as unknown.
  • A type that is not an object, next to an allOf whose members are all true (or {} when the type is not a scalar), or next to a oneOf or anyOf with an alternative that accepts any value, such as {} or true, is validated as unknown, and the model keeps the type.
  • unevaluatedProperties with a schema, on a schema without properties and additionalProperties, is typed by the model only.
  • A string part of a multipart/form-data body that has a media type, from encoding.<part>.contentType or its own contentMediaType (image/png, application/json, ...), is widened to a file or a string in the model, and the schema validates a string. The model does so for the items of an array part and for a part declared in an inline allOf, oneOf or anyOf member of the body, and not for format: binary, a const, a contentEncoding or a property of a nested object.

Some cases are not detected, so a check can still fail on them: override.zod.coerce on a recursive allOf, override.zod.strict on allOf members that declare the same key differently, and a component named like a global type, such as Date with useDates.

Usage

Parsing Data

import { CreatePetsBody } from './src/api/schemas';

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

Type Inference

import type { z } from 'zod/mini';
import { CreatePetsBody } from './src/api/schemas';

type Pet = z.infer<typeof CreatePetsBody>;

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

Safe Parsing

const result = CreatePetsBody.safeParse(unknownData);

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

Custom Validators

Sometimes, it may be valuable to add additional validation to properties with application-specific constraints. The output/override/zod parameter accepts an argument schemaExtension that allows for declaration of factory methods that produce such validators. Using schemaExtension, it is possible to append conditional custom validation to zod schema properties for specific property types and formats.

For example, an application can define an arbitrary "decimal" format for string types, containing an "x-max-precision" that limits value precision. By using a schemaExtension argument, we can declare a factory method that receives the OpenAPI object for each property matching the specified type and format. A list of validators is then returned, defining the additional refinement functions to apply to the property in the Zod schema.

orval.config.ts
import { type OpenApiSchemaObject } from 'orval';

type DecimalSchemaObject = Exclude<OpenApiSchemaObject, boolean> & {
  'x-max-precision'?: number;
};

export default defineConfig({
  petstore: {
    output: {
      override: {
        zod: {
          schemaExtension: [
            {
              // Constraint restricting what property type this validator factory applies to
              type: 'string',
              // Constraint restricting the property format. If set to "", will apply to all properties of the specified type without a format
              format: 'decimal',
              // Validator factory. Receives the entire OpenAPI Object for the property as an argument
              validatorsGenerator: (openapi_object: DecimalSchemaObject) => {
                const maxPrecision = openapi_object['x-max-precision'];
                if (maxPrecision !== undefined) {
                  // Validator that is actually appended
                  return {
                    callable: (value: unknown) => {
                      if (
                        typeof value !== 'string' ||
                        !/^[+-]?(?:\d+(\.\d*)?|\.\d+)$/.test(value)
                      ) {
                        return false;
                      }

                      const precision = value.split('.')[1]?.length ?? 0;

                      return precision === 0 || precision <= maxPrecision;
                    },

                    options: {
                      error: (issue: { input: unknown }) =>
                        `Expected a decimal with at most ${maxPrecision} fractional digits; received ${String(issue.input)}`,
                      abort: true,
                      params: { maxPrecision, format: 'decimal' },
                    },
                    // References to any values declared outside of these functions' namespaces require a binding.
                    // This allows for the value to be serialized alongside the validator.
                    bindings: { maxPrecision },
                  };
                }
                return null;
              },
            },
          ],
        },
      },
    },
  },
});

The refinement is appended to each matching property in the generated schema. In this example, bindings.maxPrecision makes the value available to both the callable and the options.error callback after serialization.

PropertyPurpose
typeOpenAPI property type to match, such as 'string'.
formatExact format to match. Use '' for properties without a format, not as a wildcard.
validatorsGeneratorFactory that receives the matching OpenAPI schema and returns a descriptor, an array of descriptors, null, or undefined.
callablePredicate appended as a Zod refinement.
optionsOptional Zod refinement options; their available fields depend on the configured Zod version.
bindingsValues referenced outside the predicate or its options callbacks that must be available in the generated code.

See samples/zod/zod-with-schema-extension for a complete sample.

Imports

You can reuse existing functions instead of embedding their implementation in the refinement. Add static import statements to bindings.$imports; Orval emits them at the top level of the generated schema file.

orval.config.ts
bindings: {
  maxPrecision,
  $imports: [
    "import { isDecimalWithPrecision as validateDecimal } from '../decimal-validator';",
  ],
},

Due to how imports are serialized, it is often wise to create an alias for the import inside of the callable, and then use that alias instead of the direct import.

orval.config.ts
if (maxPrecision !== undefined) {
  // This provides a concrete reference to the import whose direct representation may change
  const validateDecimal = isDecimalWithPrecision;

  return {
    callable: (value: unknown) =>
      typeof value === "string" &&
      validateDecimal(value, maxPrecision),

    bindings: ...
  };
}

Import paths are relative to the generated file, not orval.config.ts. If your generated schemas are in another directory, adjust the path in $imports accordingly.

Captured values such as maxPrecision still belong in bindings alongside $imports.

Combining with HTTP Clients

See the Client with Zod guide for using Zod schemas with React Query, SWR, or other HTTP clients.

On this page