Overview

Zod is a schema declaration and validation library designed with a TypeScript-first approach. Its primary function is to define the shape and types of data, then validate incoming data against these defined schemas. This process helps ensure data integrity and type safety, particularly in JavaScript and TypeScript applications where runtime data often originates from external, untyped sources like API responses, user inputs, or configuration files.

The library leverages TypeScript's type inference capabilities, meaning that once a schema is defined using Zod, TypeScript automatically understands the type of data that conforms to that schema. This eliminates the need for redundant type declarations and helps prevent common runtime errors that arise from mismatched data types. For instance, when parsing an API response, a Zod schema can define the expected structure, and Zod will both validate the data at runtime and provide TypeScript with the correct type definition for the parsed output.

Developers use Zod to create robust validation logic for various scenarios, including form validation, environmental variable parsing, and API request/response validation. It supports a wide range of data types and validation constraints, such as strings, numbers, booleans, objects, arrays, unions, intersections, and more complex custom validations. The API is designed to be fluent and composable, allowing for the construction of intricate schemas from simpler parts. Its focus on providing clear error messages also aids in debugging and improving developer experience, as issues with data validation can be quickly identified and addressed.

Zod's open-source nature means it is freely available and benefits from community contributions. It is particularly well-suited for projects that prioritize strong type safety and predictable data handling in a TypeScript environment. For developers building applications that consume external data, Zod offers a structured and type-safe method to ensure that data conforms to expected specifications before it is processed by the application logic.

Key features

  • TypeScript Inference: Automatically infers TypeScript types from defined Zod schemas, reducing boilerplate and ensuring type consistency between schema definitions and validated data.
  • Runtime Validation: Enforces data structure and type constraints at runtime, catching errors from external data sources (e.g., API responses, user input) before they impact application logic.
  • Composability: Supports building complex schemas from simpler, reusable parts using methods like .and(), .or(), .merge(), and .partial(), facilitating modular schema design.
  • Fluent API: Provides a chaining API for defining schemas and applying transformations, making schema declarations readable and intuitive.
  • Custom Validations: Allows developers to define custom validation functions using .refine() and .superRefine() for specific business logic not covered by built-in types.
  • Error Handling: Generates detailed and localized error messages, aiding in debugging and providing clear feedback for invalid data.
  • Coercion and Transformations: Includes utilities like .preprocess() and .transform() to modify input data before validation or to convert validated data into a desired format.
  • Discriminated Unions: Offers a specialized feature for validating union types where one field (the discriminator) determines the shape of the rest of the object.

Pricing

Zod is an open-source library released under the MIT license, making it free to use for both personal and commercial projects. There are no licensing fees, subscription costs, or premium features associated with its use.

Feature Details As of Date
Licensing MIT License 2026-06-24
Cost Free 2026-06-24
Support Model Community-driven (GitHub issues and discussions) 2026-06-24

For the most current information regarding Zod's open-source status and usage, refer to the Zod project homepage.

Common integrations

  • React Hook Form: Zod schemas can be integrated with React Hook Form to handle form validation, leveraging Zod's schema definition to drive client-side validation logic.
  • Express.js / Koa.js: Used in backend applications to validate incoming request bodies, query parameters, and headers, ensuring that API endpoints receive well-formed data.
  • Next.js / Remix: Applied in full-stack frameworks for both client-side and server-side validation, including validating data from API routes, loaders, and actions. The Remix documentation on form validation provides examples using various libraries including Zod.
  • tRPC: Zod schemas are often used to define input and output types for tRPC procedures, providing end-to-end type safety from the backend to the frontend.
  • dotenv-parse-variables: For parsing and validating environment variables, ensuring that critical configuration data adheres to expected types and formats at application startup.
  • OpenAPI/Swagger Generation: Tools can convert Zod schemas into OpenAPI specifications, allowing for automatic generation of API documentation and client SDKs based on defined data structures.

Alternatives

  • Joi: A powerful schema description language and data validator for JavaScript, often used in Node.js environments for server-side validation.
  • Yup: A schema builder for value parsing and validation, frequently used in conjunction with form libraries in React applications.
  • Valibot: A small, tree-shakeable schema validation library that prioritizes bundle size and performance.

Getting started

To begin using Zod, first install it via npm or yarn:

npm install zod
# or
yarn add zod

Once installed, you can define your first schema and validate data against it. The example below demonstrates defining a simple user schema with string and number types, then parsing some data.

import { z } from 'zod';

// 1. Define a schema for a User object
const UserSchema = z.object({
  id: z.string().uuid("Invalid UUID format"),
  name: z.string().min(3, "Name must be at least 3 characters long"),
  email: z.string().email("Invalid email address"),
  age: z.number().int().positive("Age must be a positive integer"),
  isActive: z.boolean().default(true),
  roles: z.array(z.enum(["admin", "editor", "viewer"])).optional(),
});

// Infer the TypeScript type from the schema
type User = z.infer;

// 2. Example data to validate
const validUserData = {
  id: "a1b2c3d4-e5f6-7890-1234-567890abcdef",
  name: "Alice Smith",
  email: "[email protected]",
  age: 30,
  isActive: true,
  roles: ["admin", "editor"]
};

const invalidUserData = {
  id: "invalid-uuid",
  name: "Al",
  email: "alice.example.com",
  age: -5,
  // isActive is missing, will use default
};

// 3. Validate the data
try {
  const user: User = UserSchema.parse(validUserData);
  console.log("Valid user data:", user);
  // Output: Valid user data: { id: '...', name: 'Alice Smith', email: '[email protected]', age: 30, isActive: true, roles: [ 'admin', 'editor' ] }
} catch (error) {
  console.error("Validation error for valid data:", error);
}

try {
  const user: User = UserSchema.parse(invalidUserData);
  console.log("Invalid user data (should not reach here):");
} catch (error) {
  console.error("Validation error for invalid data:", error.issues);
  /* Output for invalid data (error.issues):
  [ 
    { code: 'invalid_string', validation: 'uuid', message: 'Invalid UUID format', path: [ 'id' ] },
    { code: 'too_small', minimum: 3, type: 'string', inclusive: true, exact: false, message: 'Name must be at least 3 characters long', path: [ 'name' ] },
    { code: 'invalid_string', validation: 'email', message: 'Invalid email address', path: [ 'email' ] },
    { code: 'too_small', minimum: 1, type: 'number', inclusive: true, exact: false, message: 'Age must be a positive integer', path: [ 'age' ] }
  ]
  */
}

// Zod also supports safe parsing, which doesn't throw an error but returns a result object
const safeResult = UserSchema.safeParse(invalidUserData);
if (!safeResult.success) {
  console.error("Safe parse errors:", safeResult.error.issues);
} else {
  console.log("Safe parse success:", safeResult.data);
}

This example demonstrates basic schema definition for an object, including `string` with `uuid` and `min` constraints, `number` with `int` and `positive` constraints, `email` validation, `boolean` with a default value, and an optional array of `enum` values. The `z.infer` utility is used to derive the TypeScript type from the schema, and both `parse` (which throws on error) and `safeParse` (which returns a result object) methods are shown for handling validation outcomes.