| | |

Zod 29 🛡️ JSON Schema Conversion — z.toJSONSchema() for OpenAPI generation

⏱️ Estimated read: 9 min | |

OpenAPI is a JSON Schema dialect, and Zod v4 ships a native converter that turns a Zod schema into the JSON Schema object that an OpenAPI document needs. The function is z.toJSONSchema(schema, options?), and it was introduced in zod@4.0 as a built-in replacement for the separate zod-to-json-schema package that v3 projects had to install . The conversion is not a side project; it is the mechanism that OpenAPI generators use to derive request and response schemas from the same Zod schemas the application already validates with.

This chapter covers the z.toJSONSchema() API, the options that determine what the output represents, and the integration patterns that connect the converter to an OpenAPI document generator. The sections that follow walk through the conversion call and its options, the unrepresentable types that throw by default, and the framework integrations that consume the JSON Schema output.

Key point: z.toJSONSchema(schema) converts a Zod v4 schema to a JSON Schema object, defaulting to the output type and Draft 2020-12; unrepresentable types like z.date() and z.bigint() throw unless unrepresentable: "any" or an override callback supplies a replacement.


a. The conversion call and its options

z.toJSONSchema(schema, options?) returns a plain JSON Schema object. The default target is Draft 2020-12, which is the version OpenAPI 3.1 speaks natively . The function is synchronous and does not require a separate dependency, which is the difference from the v3 pattern where zod-to-json-schema had to be installed and called separately.

import { z } from "zod";

const UserSchema = z.object({
  id: z.uuid(),
  email: z.email(),
  age: z.number().int().positive().optional(),
});

const jsonSchema = z.toJSONSchema(UserSchema);
// {
//   type: "object",
//   properties: {
//     id: { type: "string", format: "uuid" },
//     email: { type: "string", format: "email" },
//     age: { type: "integer", exclusiveMinimum: 0 },
//   },
//   required: ["id", "email"],
//   additionalProperties: false,
// }

The options object controls the conversion. The io option selects the input or output type for schemas that transform or default. The target option selects the JSON Schema version. The unrepresentable option decides what happens when a Zod type has no JSON Schema equivalent. The reused option extracts repeated schemas into $defs instead of inlining them. The override option provides a callback that can modify the generated schema after the fact .

// Input type instead of output type
z.toJSONSchema(TransformedSchema, { io: "input" });

// OpenAPI 3.0 target (for older specs)
z.toJSONSchema(Schema, { target: "openapi-3.0" });

// Reused schemas into $defs
z.toJSONSchema(Schema, { reused: "ref" });

The io option is the one that matters for OpenAPI. A schema with a .default() is optional on the input side and required on the output side. A request body schema should use io: "input" so the defaulted field is not marked as required; a response schema should use the default output mode so the field is present .


b. Unrepresentable types and the error by default

Zod has types that JSON Schema cannot express. z.date() is a Date object at runtime, and JSON has no date type. z.bigint(), z.symbol(), z.map(), z.set(), and z.transform() have no JSON Schema analog either . By default, z.toJSONSchema() throws an error when it encounters one of these types, because a silent conversion would produce a schema that does not match the runtime validator.

// Throws by default
z.toJSONSchema(z.object({ createdAt: z.date() }));

// Replace unrepresentable types with {} (unknown)
z.toJSONSchema(z.object({ createdAt: z.date() }), {
  unrepresentable: "any",
});

// Supply a custom replacement
z.toJSONSchema(z.object({ createdAt: z.date() }), {
  unrepresentable: "any",
  override: (ctx) => {
    if (ctx.zodSchema._zod.def.type === "date") {
      ctx.jsonSchema.type = "string";
      ctx.jsonSchema.format = "date-time";
    }
  },
});

The override callback is the correct place to map z.date() to { type: "string", format: "date-time" }, which is what OpenAPI expects for a date-time value. The unrepresentable: "any" option is required alongside the override because the converter throws before the override runs for unrepresentable types .

The z.undefined() case is a specific edge. Starting in a v3 patch, the converter emits { not: {} } for z.undefined() to reflect that undefined is not a valid JSON value. In an OpenAPI response, this can produce an application/json schema for what should be an empty response. The fix is the same override pattern, replacing the generated schema with a description-only object for the empty response .


c. OpenAPI generation patterns

The converter is a building block, not a complete OpenAPI generator. The application or a framework adapter builds the document—the openapi version, the info block, the paths—and calls z.toJSONSchema() for each schema that appears in a request body, a parameter, or a response.

import { z } from "zod";

const UserSchema = z.object({ id: z.uuid(), email: z.email() });

const openApiDoc = {
  openapi: "3.1.0",
  info: { title: "Users API", version: "1.0.0" },
  paths: {
    "/users": {
      post: {
        requestBody: {
          content: {
            "application/json": {
              schema: z.toJSONSchema(UserSchema, { io: "input" }),
            },
          },
        },
        responses: {
          "201": {
            description: "Created",
            content: {
              "application/json": {
                schema: z.toJSONSchema(UserSchema),
              },
            },
          },
        },
      },
    },
  },
};

The frameworks that consume Zod schemas for OpenAPI have adopted z.toJSONSchema() directly. @axiomify/openapi generates OpenAPI 3.0 documentation from Axiomify routes and Zod schemas, and it supports Zod v4 natively through z.toJSONSchema() . The standard-openapi package, which converts Standard Schema validators to OpenAPI schemas, requires no additional package for Zod v4 because it uses the built-in converter . The Scalar documentation shows a Next.js route handler that uses z.toJSONSchema(planetsSchema) inside a manually constructed OpenAPI document .

The reused: "ref" option is what keeps a large document from duplicating schemas. When the same schema appears in multiple places—a User schema in both the request and the response—the converter can extract it into $defs and reference it with $ref. The OpenAPI generator then relocates the $defs into components/schemas and rewrites the pointers, which is the pattern that @setu-ts/openapi-plugin documents . A schema reused as a parameter is never hoisted to a $ref, because a parameter list is built by destructuring the object’s properties and a $ref has none .


Complete Example Session

// ============================================
// PART 1: THE SCHEMA
// ============================================
import { z } from "zod";

const CreateUserSchema = z.object({
  email: z.email(),
  name: z.string().min(2).max(100),
  age: z.number().int().positive().optional(),
});

// ============================================
// PART 2: THE REQUEST SCHEMA (INPUT)
// ============================================
const requestSchema = z.toJSONSchema(CreateUserSchema, {
  io: "input",
  target: "openapi-3.0",
});
// age is optional; email/name are required

// ============================================
// PART 3: THE RESPONSE SCHEMA (OUTPUT)
// ============================================
const UserSchema = z.object({
  id: z.uuid(),
  email: z.email(),
  name: z.string(),
  createdAt: z.date(),
});

const responseSchema = z.toJSONSchema(UserSchema, {
  unrepresentable: "any",
  override: (ctx) => {
    if (ctx.zodSchema._zod.def.type === "date") {
      ctx.jsonSchema.type = "string";
      ctx.jsonSchema.format = "date-time";
    }
  },
});
// createdAt becomes { type: "string", format: "date-time" }

// ============================================
// PART 4: THE OPENAPI DOCUMENT
// ============================================
const doc = {
  openapi: "3.1.0",
  info: { title: "Users API", version: "1.0.0" },
  paths: {
    "/users": {
      post: {
        requestBody: {
          content: { "application/json": { schema: requestSchema } },
        },
        responses: {
          "201": {
            description: "Created",
            content: { "application/json": { schema: responseSchema } },
          },
        },
      },
    },
  },
};

The parts covered the schema, the input projection, the output projection with the date override, and the assembled OpenAPI document.


Quick Reference

Conversion Options

OptionValuesDefault
io"input", "output""output"
target"draft-04", "draft-07", "draft-2020-12", "openapi-3.0""draft-2020-12"
unrepresentable"throw", "any", handler function"throw"
reused"inline", "ref""inline"
metadataRegistryz.globalRegistry

Unrepresentable Types

Zod TypeJSON Schema
z.date()Throws; map to { type: "string", format: "date-time" } via override
z.bigint()Throws; map to { type: "string" }
z.symbol()Throws
z.map() / z.set()Throws
z.undefined(){ not: {} }

OpenAPI Framework Adapters

PackageUses z.toJSONSchema()
@axiomify/openapiYes
standard-openapiYes, no extra package for v4
@setu-ts/openapi-pluginYes
Scalar (manual doc)Yes

Best Practices

✅ Do This:

// Use io: "input" for request bodies
z.toJSONSchema(Schema, { io: "input" })                       // ✅

// Map unrepresentable types with override
z.toJSONSchema(Schema, { unrepresentable: "any", override: mapDate }) // ✅

// Use reused: "ref" for large documents
z.toJSONSchema(Schema, { reused: "ref" })                     // ✅

❌ Don’t Do This:

// Convert z.date() without handling it
z.toJSONSchema(z.object({ createdAt: z.date() })); // throws   // ❌

// Use output mode for a request schema with defaults
// (required fields that are optional on input)                // ❌

// Assume the converter builds the whole OpenAPI document
// (it produces one schema, not the paths/info)                // ❌

Common Pitfalls

PitfallWhy It HappensFix
Conversion throws on z.date()Unrepresentable by defaultunrepresentable: "any" + override
Request schema marks defaults as requiredio: "output" defaultUse io: "input"
Duplicated schemas in the documentreused: "inline" defaultUse reused: "ref"
Empty response has an application/json schemaz.undefined() emits { not: {} }Override to a description-only schema
OpenAPI 3.0 rejects the schemaDraft 2020-12 defaultSet target: "openapi-3.0"

Real-World Examples

1. Basic conversion

z.toJSONSchema(z.object({ name: z.string() }));

2. Input projection

z.toJSONSchema(Schema, { io: "input" });

3. OpenAPI 3.0 target

z.toJSONSchema(Schema, { target: "openapi-3.0" });

4. Date override

override: (ctx) => { if (isDate) { ctx.jsonSchema.type = "string"; ctx.jsonSchema.format = "date-time"; } }

5. Reused refs

z.toJSONSchema(Schema, { reused: "ref" });

6. Unrepresentable as any

z.toJSONSchema(Schema, { unrepresentable: "any" });

7. Response schema in a route

schema: z.toJSONSchema(planetsSchema)

8. Axiomify adapter

useOpenAPI(app, { info: { title: "API", version: "1.0.0" } });

9. Standard OpenAPI with Zod v4

import { toOpenAPISchema } from "@standard-community/standard-openapi";

10. Undefined response override

override: (ctx) => { if (type === "undefined") { /* description only */ } }

Visual

The Conversion Flow

┌─────────────────────────────────────────────────────────┐
│  Zod Schema                                             │
│         │                                               │
│         ▼                                               │
│  z.toJSONSchema(schema, options)                        │
│         │                                               │
│         ▼                                               │
│  JSON Schema object                                     │
│         │                                               │
│         ▼                                               │
│  OpenAPI document builder                               │
│  (paths, info, components)                              │
└─────────────────────────────────────────────────────────┘

Input vs Output

┌─────────────────────────────────────────────────────────┐
│  Schema: z.object({ age: z.number().default(0) })       │
│                                                         │
│  io: "input"                io: "output" (default)      │
│  age is optional            age is required             │
│  (request body)             (response body)             │
└─────────────────────────────────────────────────────────┘

Unrepresentable Handling

┌─────────────────────────────────────────────────────────┐
│  z.date()                                               │
│         │                                               │
│    ┌────┴────┐                                          │
│    ▼         ▼                                          │
│  default   unrepresentable: "any"                       │
│    │         │                                          │
│    ▼         ▼                                          │
│  THROW     {} (unknown)                                 │
│            or override                                  │
│            → { type: "string", format: "date-time" }    │
└─────────────────────────────────────────────────────────┘

OpenAPI Assembly

┌─────────────────────────────────────────────────────────┐
│  {                                                      │
│    openapi: "3.1.0",                                    │
│    info: { title, version },                            │
│    paths: {                                             │
│      "/users": {                                        │
│        post: {                                          │
│          requestBody: { schema: toJSONSchema(req) },    │
│          responses: { 201: { schema: toJSONSchema(res) }}│
│        }                                                │
│      }                                                  │
│    }                                                    │
│  }                                                      │
└─────────────────────────────────────────────────────────┘

Summary

ItemValue
Functionz.toJSONSchema(schema, options?)
Introducedzod@4.0
Default targetDraft 2020-12
Default io"output"
Unrepresentable defaultThrows
Date mappingoverride → { type: "string", format: "date-time" }
Reused schemasreused: "ref" → $defs
OpenAPI 3.0 targettarget: "openapi-3.0"

Key takeaways:

  • z.toJSONSchema() is native in Zod v4. It replaces the zod-to-json-schema package that v3 projects used, and it defaults to the output type and Draft 2020-12 .
  • io: "input" is for request bodies. A schema with defaults is optional on the input side and required on the output side. The request schema uses the input projection; the response schema uses the default .
  • Unrepresentable types throw by default. z.date(), z.bigint(), and the other types without a JSON Schema analog need unrepresentable: "any" plus an override callback that supplies the replacement .
  • The converter produces one schema, not the whole document. The application or a framework adapter builds the openapi, info, and paths around the converted schemas. @axiomify/openapi and standard-openapi are examples of adapters that consume the output .
  • reused: "ref" prevents duplication. A schema that appears in multiple places is extracted into $defs and referenced with $ref, which the OpenAPI generator relocates into components/schemas .

Remember: z.toJSONSchema() is the bridge between the schema the application validates with and the schema the OpenAPI document describes. It is a converter, not a generator: it produces the JSON Schema object, and the document builder places it. Use io: "input" for requests, handle the unrepresentable types with override, and set the target to match the OpenAPI version. When a type throws, the message is the converter refusing to produce a schema that does not match the runtime check; the fix is an override, not a catch.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!