Zod TypeScript Schema Validation

VerifiedSafe

Validate data at runtime and infer TypeScript types with Zod 4: objects, safeParse, coercion, discriminated unions, JSON Schema output and v3-to-v4 migration.

Sby Skills Guide Bot
DevelopmentIntermediate
11/17/2026
Claude CodeCursorWindsurfCopilotCodex
#validation#schema#typescript#type-inference#parsing

Recommended for

Automated summary

This skill documents Zod 4, a TypeScript library that derives both a runtime validator and a static type from a single schema, covering the v4 API and migration from v3.

Strengths

  • Covers concrete API surface: z.object, safeParse, coercion, discriminated unions, refinements and z.infer
  • Explicitly flags v4 deprecations (z.string().email(), .merge(), .strict(), err.flatten()) with their replacements
  • Includes an end-to-end HTTP handler example showing error formatting with z.flattenError
  • Notes advanced uses: z.toJSONSchema for LLM tool calling, bidirectional z.codec, and getter-based recursive schemas

Limitations

  • The code example is cut off mid-output (the 400 response body is incomplete), hurting copy-paste use
  • No dedicated v3-to-v4 migration checklist or before/after comparison table
  • Assumes TypeScript 5.5+ in strict mode and does not address untyped JavaScript projects
When to use it

Reach for it when writing or reviewing TypeScript validation code with Zod, especially when upgrading to v4 or parsing untrusted input.

When not to use it

Skip it if you need a comparison of validation libraries (Yup, Valibot, ArkType) or a beginner tutorial starting from zero.

Security analysis

Safe
Quality score88/100

The content is pure reference documentation for the Zod validation library. It contains no tool invocations, no shell commands, no network or filesystem operations, and no instructions to the agent beyond describing library APIs. Code samples are illustrative TypeScript that validates data locally (safeParse, env validation) and pose no execution risk. No prompt-injection or role-manipulation attempts were present.

No concerns found

How this analysis is made

name: zod description: >- Zod is a TypeScript-first schema library that validates data at runtime and infers static types from the same schema. Use when validating API request bodies, form input, environment variables or config files, parsing untrusted JSON, or migrating from Zod 3 to Zod 4. Covers z.object, safeParse, z.infer, coercion, discriminated unions, refinements, JSON Schema output and the v4 API changes. license: Apache-2.0 compatibility: "TypeScript 5.5+ with strict mode; zod 4.x (npm install zod)" metadata: author: terminal-skills version: "1.1.0" category: development tags: "validation, schema, typescript, type-inference, parsing" repository: "https://github.com/colinhacks/zod"

Zod

Overview

Zod defines a schema once and gives you both a runtime validator and the TypeScript type (z.infer). The current major version is Zod 4 (zod@4.6.7 checked on 2026-10-12); import { z } from "zod" now resolves to v4. Zod 3 remains importable from "zod/v3", and a tree-shakeable functional variant lives at "zod/mini". Zod 4 deprecates several v3 spellings (listed in Guidelines), which is the main source of outdated code in the wild. Zod also produces JSON Schema with z.toJSONSchema(schema), which is how many LLM tool-calling libraries consume it.

Instructions

  1. Install with npm install zod. Enable "strict": true in tsconfig.
  2. Define schemas with z.object, z.string(), z.number(), z.enum([...]), z.array(), z.record(keySchema, valueSchema) (both arguments are required in v4; the one-argument form is a type error) and infer types with type User = z.infer<typeof User>.
  3. Prefer top-level string formats: z.email(), z.url(), z.uuid(), z.iso.datetime(). The method forms (z.string().email()) still work but are deprecated.
  4. Parse untrusted data with schema.safeParse(data) and branch on result.success; schema.parse throws a ZodError. Use parseAsync / safeParseAsync when a refinement or transform is async.
  5. Format errors with z.flattenError(err) ({ formErrors, fieldErrors }), z.treeifyError(err) or z.prettifyError(err). The err.flatten() and err.format() methods are deprecated. Custom messages: z.string().min(8, "At least 8 characters") or { error: "..." }; .refine(fn, "message") for custom rules.
  6. Coerce strings from query strings and env vars with z.coerce.number(), z.coerce.boolean() (any non-empty string is true, including "false"), z.coerce.date().
  7. Combine schemas with .extend(), .pick(), .omit(), .partial(); use .safeExtend() when the schema carries refinements. .merge() is deprecated; spread A.shape or use .extend(B.shape).
  8. Use z.discriminatedUnion("type", [...]) for tagged unions and z.strictObject / z.looseObject instead of .strict() / .passthrough().
  9. Recursive schemas use getters in v4, no z.lazy or manual type annotation needed.
  10. Transform and chain with .transform() and .pipe(); bidirectional conversions use z.codec(inputSchema, outputSchema, { decode, encode }).

Examples

Example 1: Validate a signup request

User request: "Validate the POST /signup body and return field errors."

import { z } from "zod";

export const Signup = z.object({
  name: z.string().min(1, "Name is required"),
  email: z.email("Invalid email"),
  website: z.url().optional(),
  role: z.enum(["user", "admin"]).default("user"),
  tags: z.array(z.string()).max(10).default([]),
});
export type Signup = z.infer<typeof Signup>;

app.post("/signup", (req, res) => {
  const parsed = Signup.safeParse(req.body);
  if (!parsed.success) {
    return res.status(400).json({ errors: z.flattenError(parsed.error).fieldErrors });
  }
  createUser(parsed.data); // typed as Signup, defaults applied
});

Result: a body of { "email": "x", "website": "nope" } returns 400 with {"errors":{"name":["Invalid input: expected string, received undefined"],"email":["Invalid email"],"website":["Invalid URL"]}}.

Example 2: Fail fast on bad environment variables

User request: "Validate process.env at startup and convert PORT to a number."

import { z } from "zod";

const Env = z.object({
  DATABASE_URL: z.url(),
  STRIPE_API_KEY: z.string().min(1),
  PORT: z.coerce.number().default(3000),
  NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
});

const parsed = Env.safeParse(process.env);
if (!parsed.success) {
  console.error(z.prettifyError(parsed.error));
  process.exit(1);
}
export const env = parsed.data;

Result: a missing DATABASE_URL prints a ✖ ... → at DATABASE_URL line and exits; otherwise env.PORT is the number 3000.

Example 3: Recursive schema and JSON Schema output

const Category = z.object({
  name: z.string(),
  get children() { return z.array(Category).default([]); },
});
Category.parse({ name: "Tools", children: [{ name: "Drills" }] });
// { name: "Tools", children: [ { name: "Drills", children: [] } ] }

const schema = z.toJSONSchema(z.object({ city: z.string() }));
// { "$schema": ".../draft/2020-12/schema", type: "object", properties: {...}, required: ["city"], additionalProperties: false }

Guidelines

  • Check the installed major version first. In v4 .default() short-circuits: the default is returned without running the schema, and it must match the output type.
  • Deprecated in v4: z.string().email()/url()/uuid(), err.flatten()/format(), .merge(), .strict()/.passthrough(), z.nativeEnum (use z.enum with an enum object), message: parameter (use error:).
  • z.coerce.* accepts any input, so the inferred input type is unknown; validate strings before coercion when the type matters.
  • Validate at boundaries only (requests, env, files, third-party API responses); do not re-parse the same data between internal functions.
  • Never echo raw ZodError objects to clients if input may contain secrets; return field messages instead.
  • Libraries that peer-depend on Zod 3 may break on v4; import from "zod/v3" for them until updated.

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/zod-typescript-schema-validation-mwirmdyd/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/zod-typescript-schema-validation-mwirmdyd' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/zod-typescript-schema-validation-mwirmdyd/download' --output '.skill-downloads/zod-typescript-schema-validation-mwirmdyd/SKILL.md.part' && mv '.skill-downloads/zod-typescript-schema-validation-mwirmdyd/SKILL.md.part' '.skill-downloads/zod-typescript-schema-validation-mwirmdyd/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

Environment declared by the author: TypeScript 5.5+ with strict mode; zod 4.x (npm install zod)

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/zod-typescript-schema-validation-mwirmdyd/SKILL.md' && test -s '.skill-downloads/zod-typescript-schema-validation-mwirmdyd/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/zod' && cp -R '.skill-downloads/zod-typescript-schema-validation-mwirmdyd' '.claude/skills/zod'

Cursor
test -f '.skill-downloads/zod-typescript-schema-validation-mwirmdyd/SKILL.md' && test -s '.skill-downloads/zod-typescript-schema-validation-mwirmdyd/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/zod' && cp -R '.skill-downloads/zod-typescript-schema-validation-mwirmdyd' '.cursor/skills/zod'

Codex
test -f '.skill-downloads/zod-typescript-schema-validation-mwirmdyd/SKILL.md' && test -s '.skill-downloads/zod-typescript-schema-validation-mwirmdyd/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/zod' && cp -R '.skill-downloads/zod-typescript-schema-validation-mwirmdyd' '.agents/skills/zod'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/zod-typescript-schema-validation-mwirmdyd'

openskills read 'zod-typescript-schema-validation-mwirmdyd'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/zod-typescript-schema-validation-mwirmdyd/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills