Zod

Zod Docs

Zod is a TypeScript-first schema declaration and validation library. It’s used to define the shape and type of data at runtime, while giving full type inference at compile-time—so you get both static and dynamic validation in one place.

Why use Zod?

When building TypeScript applications, TypeScript alone can’t validate external data (e.g. from an API, form input, or a file). Zod fills this gap:

Key Features

Integration Use Cases

Core Zod Terms

schema: A blueprint that defines the shape, types, and rules for a piece of data. Like saying: “I expect an object with a string name, a number age, etc.”

z.object(): A function in Zod that creates a schema for an object with specific keys and value types.

z.string(): A function that defines a schema for a string.

z.number(): A schema that matches numbers. You can add methods like .int() (integer only) or .positive() (must be > 0).

z.email(): Validates that a string is a valid email address format.

z.optional(): Makes a field not required (can be missing).

z.default(): Provides a default value if none is supplied.

z.length(n): Validates that a string or array has exactly n elements.

safeParse(): A method that validates some unknown data against a schema, but does not throw errors. Instead, it returns an object with a success flag and either the valid data or a formatted error.

result.success: A boolean—true if the data passed validation, false if it failed.

result.data: The parsed (validated and typed) data if validation succeeded.

result.error: Contains error details if validation failed.

TypeScript & Programming Concepts

Type inference: TypeScript automatically figures out the types based on your Zod schema—no need to write extra type annotations.

Runtime validation: Checking data while the app is running, e.g., when receiving input from a user or API.

Static typing: Type checking at development time, before you even run the code.

Parse: In Zod, “parsing” means both validating and transforming data.

Composability: Ability to build more complex things by combining simpler parts (e.g., combining multiple schemas into one).

Sanitize: Clean or reject invalid data before using it.

API: Application Programming Interface—communication between your app and another service or backend.

Contract: The agreed structure of data shared between systems (e.g., what your frontend expects from your backend).