Zod
Generate Zod schemas from OpenAPI
Generate Zod schemas from your OpenAPI specification for runtime validation.
Configuration
Set the client option to zod:
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 allIn 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:
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',
},
},
});| Value | Output |
|---|---|
4 | Always emit Zod 4 syntax, regardless of the installed zod version. |
3 | Always 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 nozodversion can be detected; - when a branch is coerced, since coercion can make branches overlap (
"42"passes bothzod.string()andzod.coerce.number()); - when a branch renders looser than the spec (
{}, arequired-only branch, or a keyword Orval drops such asnot), since two loose branches would both match; - when it has a
discriminator, which is emitted aszod.discriminatedUnion(...)instead whengenerateDiscriminatedUnionis enabled.
Zod Mini
Set override.zod.variant to 'mini' to generate schemas against Zod Mini:
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.
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 aoneOf/anyOfbranch next to siblingproperties),if/then/else,patternProperties,propertyNames,dependentSchemas,dependencies,unevaluatedProperties,unevaluatedItems,contains,minContains,maxContains,uniqueItems,minProperties,maxProperties,additionalItemsandcontentSchema.dependentRequiredfails 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 arrayconst, anditemsgiven as a list. - A
oneOfthat renders as a plain union, unless its alternatives have distinct types, literals or discriminator values. WithoutgenerateXorthe error says to turn it on. A coerced alternative also renders theoneOfas a plain union. - More than one composition keyword on the same schema, as only the first of
allOf,oneOfandanyOfis rendered. - An
allOfof objects merged into one object, withstrictor in a discriminated union, that declares the same property, oradditionalProperties, 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 aformat: only its items and bounds are rendered. - An unresolvable
$refor$dynamicRef, and a circular$refthat is inlined, since all are validated as unknown. WithoutgenerateReusableSchemasthe error says to turn it on. - A
formatzod does not check, such asformat: phone, unlessformatTypemaps it. The checked formats aredate,time,time-local,date-time,date-time-local,email,uri,hostname,uuid,ipv4,ipv6andbinary, plus the number formatsint32,int64,floatanddoublethrough the number type. AcontentEncoding, such asbase64, 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):
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:
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
anyon 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.tsof the models and needs it to export every component by name. KeepindexFileson, which is the default, in the configuration that writes the models. - An option such as
formatTypeoruseDatesthat maps a type in the schemas must map it in the models too. SetuseBigIntanduseReadonlyArraysin both configurations, so the checks skip the components they change. - With
exactOptionalPropertyTypesin yourtsconfig, the models type an optional property asa?: T, so setexactOptional: trueinoverride.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 thetsconfigit reads sets the flag andexactOptionalis off, and when the Zod version it detects is below 4.3, where no setting ofexactOptionalsatisfies it: upgrade Zod, or setexactOptional: falseand turn the flag off. modelTypeChecksrejectsuseBrandedTypes,useNullForOptionalandenumGenerationType: 'enum'with an error, because they shape the models in ways a Zod output cannot match. A TypeScriptenumis not assignable from the string literals a schema outputs, so use'const'or'union'in the configuration that writes the models too.namingConvention.propertiesis 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
readOnlyarray withitemsisreadonly T[]in the model, and a Zod schema outputsT[]. - A
defaulton an optional property makes the key required in the output only. additionalPropertiesnext topropertiesis typed asunknownby the model, and the schema checks it.- For an object with
additionalProperties: falseand a finite set of optional properties,minProperties: 1requires one of those properties in the model. The generated validator still accepts{}. - A schema without a type, such as
{}or one with only adescription, is validated asunknown, and the model types it as{}. - A component without a type that only has
patternProperties, an emptypropertiesoradditionalProperties: falseis validated asunknown, and the model types it as an object. Zod keeps a record foradditionalPropertieswith a schema ortrue, and a property or a member of that kind is untyped in the model too. - A
constthat is an object or an array is not validated. - A
constwithnullin itstypeis typed withoutnullby the model. - A component whose properties are all a
constis written as a constant object by the model, so every key is required. A component with an optional one differs from the schema. - A
oneOforanyOfwith anull, nullable orenumalternative, next to thepropertiesorallOfof the same schema: the model merges the alternatives and drops the own properties of an enum, and the schema intersects them. - An
allOfwith anenummember, next topropertiesof the same schema: the model makes the member and the own properties alternatives, and the schema intersects them. - A
$refto anything but a whole component schema, such as#/paths/...or#/components/responses/..., is validated asunknown. - A
oneOforanyOfalternative that only requires keys, such as{ required: [id] }, next to thepropertiesof an object, is validated as an object with those keys, and the model types it asunknown. - With
useBigInt, a 64-bit integer (format: int64oruint64) is abigintin the model and anumberin the schema. - With
useReadonlyArrays, an array isreadonlyin the model, and the schema output is not. - A tuple (
prefixItems) withitemsand amaxItemsthat 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 asunknownafter that, so a component on such a cycle has no assertion. - A
typewithnullthat is not an object type ('null'or['null', 'string']) next toallOf,oneOforanyOf: Zod validates the composition and drops thenull. A['object', 'null']type keeps it and has an assertion. - With Zod 3, a required property without a type (
{},trueor a reference to it, one with only adescriptionor anot, an object shape such asadditionalProperties: false, or aoneOfwith such a member) is optional in the output, and the model requires it, also when the property and therequiredlist sit in differentallOfmembers. Zod 4 keeps the key required. - With Zod 3, an
enumwith no primitive member (empty, or with objects and arrays only) is validated asnever. - A
constnext to a stringformat(email,uuid, ...) is validated as the format, not as the literal, and a binary string (format: binary, orcontentMediaType: application/octet-streamwithout acontentEncoding) with aconstis validated as a file. items: falsewithoutprefixItemsisunknown[]in the model andnever[]in the schema.- A
notof an empty schema (not: {}) is validated asnever, and the model types it asunknown. - A
typethat is not an object, next to anallOfwhose members are alltrue(or{}when the type is not a scalar), or next to aoneOforanyOfwith an alternative that accepts any value, such as{}ortrue, is validated asunknown, and the model keeps the type. unevaluatedPropertieswith a schema, on a schema withoutpropertiesandadditionalProperties, is typed by the model only.- A string part of a
multipart/form-databody that has a media type, fromencoding.<part>.contentTypeor its owncontentMediaType(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 inlineallOf,oneOforanyOfmember of the body, and not forformat: binary, aconst, acontentEncodingor 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.
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.
| Property | Purpose |
|---|---|
type | OpenAPI property type to match, such as 'string'. |
format | Exact format to match. Use '' for properties without a format, not as a wildcard. |
validatorsGenerator | Factory that receives the matching OpenAPI schema and returns a descriptor, an array of descriptors, null, or undefined. |
callable | Predicate appended as a Zod refinement. |
options | Optional Zod refinement options; their available fields depend on the configured Zod version. |
bindings | Values 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.
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.
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.