惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Security Archives - TechRepublic
Security Archives - TechRepublic
Forbes - Security
Forbes - Security
C
Cyber Attacks, Cyber Crime and Cyber Security
Latest news
Latest news
V2EX - 技术
V2EX - 技术
Google DeepMind News
Google DeepMind News
Cyberwarzone
Cyberwarzone
Vercel News
Vercel News
V
Vulnerabilities – Threatpost
I
InfoQ
GbyAI
GbyAI
有赞技术团队
有赞技术团队
雷峰网
雷峰网
阮一峰的网络日志
阮一峰的网络日志
A
Arctic Wolf
F
Full Disclosure
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
Check Point Blog
Hugging Face - Blog
Hugging Face - Blog
Simon Willison's Weblog
Simon Willison's Weblog
Google DeepMind News
Google DeepMind News
M
MIT News - Artificial intelligence
Engineering at Meta
Engineering at Meta
The Register - Security
The Register - Security
T
Tor Project blog
T
Troy Hunt's Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
S
Security Affairs
W
WeLiveSecurity
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Stack Overflow Blog
Stack Overflow Blog
Apple Machine Learning Research
Apple Machine Learning Research
H
Heimdal Security Blog
S
Secure Thoughts
Y
Y Combinator Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Security Latest
Security Latest
Martin Fowler
Martin Fowler
G
Google Developers Blog
宝玉的分享
宝玉的分享
腾讯CDC
TaoSecurity Blog
TaoSecurity Blog
T
Threatpost
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Project Zero
Project Zero
Blog — PlanetScale
Blog — PlanetScale
大猫的无限游戏
大猫的无限游戏
MongoDB | Blog
MongoDB | Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Zod Validation: Type-Safe APIs & Forms in TypeScript (Complete Guide)
Anup Karanjk · 2026-05-22 · via DEV Community

TypeScript types disappear at runtime. Your carefully typed User interface means nothing when the JSON from an external API, a form submission, or a database query arrives as unknown. Zod bridges this gap: you define a schema once, validate data against it at runtime, and get a TypeScript type back for free. This guide covers every Zod pattern you will use — from basic schemas to API validation, form handling, and OpenAPI generation.

If you are building TypeScript APIs or form-heavy applications, browse WOWHOW Tools for starter kits and check out the full catalog for Next.js and React templates with validation built in.

Why Zod Over Alternatives

Zod infers TypeScript types from schemas (schema-first, not type-first). It has zero dependencies, works in Node.js and browsers, and its error messages are structured objects you can use to build user-facing form errors without any extra work. It also chains neatly with transforms — parse, validate, and reshape data in one step.

Core Schema Types

import { z } from 'zod'

// primitives
const name    = z.string()
const age     = z.number()
const active  = z.boolean()
const created = z.date()
const id      = z.bigint()

// string constraints
const email    = z.string().email()
const url      = z.string().url()
const uuid     = z.string().uuid()
const slug     = z.string().regex(/^[a-z0-9-]+$/, 'Lowercase letters, numbers, hyphens only')
const password = z.string().min(8).max(128)
const bio      = z.string().max(500).optional()

// number constraints
const price    = z.number().positive().finite()
const rating   = z.number().int().min(1).max(5)
const quantity = z.number().int().nonnegative()

// literals and enums
const role     = z.enum(['admin', 'editor', 'viewer'])
const status   = z.literal('active')
const exact    = z.union([z.literal('pending'), z.literal('shipped'), z.literal('delivered')])

// infer types automatically
type Role   = z.infer   // 'admin' | 'editor' | 'viewer'
type Email  = z.infer  // string (with runtime guarantee)

Enter fullscreen mode Exit fullscreen mode

Object Schemas

const UserSchema = z.object({
  id:         z.string().uuid(),
  email:      z.string().email().toLowerCase(),  // transform to lowercase
  firstName:  z.string().min(1).max(50),
  lastName:   z.string().min(1).max(50),
  role:       z.enum(['admin', 'editor', 'viewer']).default('viewer'),
  age:        z.number().int().min(13).max(120).optional(),
  createdAt:  z.string().datetime(),  // ISO 8601 string
})

type User = z.infer

// parse: throws ZodError on failure
const user = UserSchema.parse(rawData)

// safeParse: returns { success, data } or { success, error }
const result = UserSchema.safeParse(rawData)
if (!result.success) {
  console.error(result.error.flatten())
  // { fieldErrors: { email: ['Invalid email'] }, formErrors: [] }
}

Enter fullscreen mode Exit fullscreen mode

Nested Objects and Arrays

const AddressSchema = z.object({
  street:  z.string().min(1),
  city:    z.string().min(1),
  state:   z.string().length(2),
  zipCode: z.string().regex(/^d{5}(-d{4})?$/),
  country: z.string().length(2).default('US'),
})

const OrderSchema = z.object({
  id:          z.string().uuid(),
  customerId:  z.string().uuid(),
  items:       z.array(
    z.object({
      productId: z.string().uuid(),
      quantity:  z.number().int().positive(),
      unitPrice: z.number().positive(),
    })
  ).min(1, 'Order must have at least one item'),
  shippingAddress: AddressSchema,
  total:       z.number().positive(),
  status:      z.enum(['pending', 'confirmed', 'shipped', 'delivered', 'cancelled']),
  notes:       z.string().max(1000).nullable().default(null),
})

type Order = z.infer

// tuple with mixed types
const CoordSchema = z.tuple([z.number(), z.number()])  // [lat, lng]
const TripleSchema = z.tuple([z.string(), z.number(), z.boolean()])

Enter fullscreen mode Exit fullscreen mode

Transforms: Parse and Reshape in One Step

// coerce strings from form inputs
const FormPriceSchema = z
  .string()
  .transform((val) => parseFloat(val))
  .pipe(z.number().positive())

// parse ISO date strings into Date objects
const DateFromStringSchema = z
  .string()
  .datetime()
  .transform((str) => new Date(str))

// normalize phone numbers
const PhoneSchema = z
  .string()
  .transform((val) => val.replace(/[^0-9]/g, ''))
  .pipe(z.string().length(10, 'Must be 10 digits'))

// computed fields using transform
const FullNameSchema = z
  .object({
    firstName: z.string(),
    lastName:  z.string(),
  })
  .transform((data) => ({
    ...data,
    fullName: `\${data.firstName} \${data.lastName}`,
    initials: `\${data.firstName[0]}.\${data.lastName[0]}.`,
  }))

const { firstName, lastName, fullName, initials } = FullNameSchema.parse({
  firstName: 'Anup',
  lastName:  'Karanjkar',
})
// fullName: 'Anup Karanjkar', initials: 'A.K.'

Enter fullscreen mode Exit fullscreen mode

Refinements: Cross-Field and Async Validation

// single-field refinement
const PasswordSchema = z
  .string()
  .min(8)
  .refine(
    (val) => /[A-Z]/.test(val) && /[0-9]/.test(val) && /[^a-zA-Z0-9]/.test(val),
    { message: 'Password must contain uppercase, number, and special character' }
  )

// cross-field refinement
const PasswordConfirmSchema = z
  .object({
    password:        z.string().min(8),
    confirmPassword: z.string(),
  })
  .refine((data) => data.password === data.confirmPassword, {
    message: 'Passwords do not match',
    path: ['confirmPassword'],   // attach error to specific field
  })

// date range validation
const DateRangeSchema = z
  .object({
    startDate: z.string().date(),
    endDate:   z.string().date(),
  })
  .refine(
    (data) => new Date(data.endDate) > new Date(data.startDate),
    { message: 'End date must be after start date', path: ['endDate'] }
  )

// async refinement (e.g. database uniqueness check)
const UniqueEmailSchema = z
  .string()
  .email()
  .superRefine(async (email, ctx) => {
    const exists = await db.user.findUnique({ where: { email } })
    if (exists) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: 'Email already in use',
      })
    }
  })

// use parseAsync for schemas with async refinements
const validEmail = await UniqueEmailSchema.parseAsync('user@example.com')

Enter fullscreen mode Exit fullscreen mode

API Request Validation in Next.js Route Handlers

import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'

const CreateProductSchema = z.object({
  name:        z.string().min(3).max(100),
  price:       z.number().positive(),
  currency:    z.enum(['USD', 'INR', 'EUR']).default('USD'),
  description: z.string().min(10).max(5000),
  tags:        z.array(z.string()).max(10).default([]),
  published:   z.boolean().default(false),
})

type CreateProductInput = z.infer

export async function POST(req: NextRequest) {
  let body: unknown
  try {
    body = await req.json()
  } catch {
    return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
  }

  const result = CreateProductSchema.safeParse(body)
  if (!result.success) {
    return NextResponse.json(
      {
        error: 'Validation failed',
        details: result.error.flatten().fieldErrors,
      },
      { status: 422 }
    )
  }

  const product = await createProduct(result.data)
  return NextResponse.json(product, { status: 201 })
}

// helper to validate any route handler input
function validateBody(schema: z.ZodType) {
  return async (req: NextRequest): Promise => {
    let body: unknown
    try {
      body = await req.json()
    } catch {
      return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
    }
    const result = schema.safeParse(body)
    if (!result.success) {
      return NextResponse.json(
        { error: 'Validation failed', details: result.error.flatten().fieldErrors },
        { status: 422 }
      )
    }
    return { data: result.data }
  }
}

Enter fullscreen mode Exit fullscreen mode

Form Validation with React Hook Form

import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'

const CheckoutSchema = z.object({
  email:     z.string().email('Enter a valid email'),
  firstName: z.string().min(1, 'Required').max(50),
  lastName:  z.string().min(1, 'Required').max(50),
  address:   z.string().min(5, 'Enter full address'),
  city:      z.string().min(1, 'Required'),
  pinCode:   z.string().regex(/^d{6}$/, 'Enter 6-digit PIN code'),
  phone:     z.string().regex(/^[6-9]d{9}$/, 'Enter valid Indian mobile number'),
})

type CheckoutFormData = z.infer

function CheckoutForm() {
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm({
    resolver: zodResolver(CheckoutSchema),
  })

  const onSubmit = async (data: CheckoutFormData) => {
    // data is fully typed AND validated
    await submitOrder(data)
  }

  return (


      {errors.email && 
{errors.email.message}
}


      {errors.pinCode && 
{errors.pinCode.message}
}


        {isSubmitting ? 'Processing...' : 'Place Order'}


  )
}

Enter fullscreen mode Exit fullscreen mode

Schema Composition and Reuse

// base schema — shared fields
const TimestampedSchema = z.object({
  createdAt: z.string().datetime(),
  updatedAt: z.string().datetime(),
})

const BaseEntitySchema = z.object({
  id: z.string().uuid(),
}).merge(TimestampedSchema)

// extend for specific entities
const ProductSchema = BaseEntitySchema.extend({
  name:  z.string(),
  price: z.number().positive(),
})

// pick/omit for partial schemas
const ProductPreviewSchema = ProductSchema.pick({ id: true, name: true })
const CreateProductInput   = ProductSchema.omit({ id: true, createdAt: true, updatedAt: true })
const UpdateProductInput   = CreateProductInput.partial()  // all fields optional

// discriminated unions
const ApiResponseSchema = z.discriminatedUnion('success', [
  z.object({ success: z.literal(true),  data: z.unknown() }),
  z.object({ success: z.literal(false), error: z.string(), code: z.number() }),
])

type ApiResponse = z.infer

Enter fullscreen mode Exit fullscreen mode

Environment Variable Validation

// src/env.ts — validate at startup, not at request time
import { z } from 'zod'

const EnvSchema = z.object({
  NODE_ENV:        z.enum(['development', 'test', 'production']),
  DATABASE_URL:    z.string().url(),
  REDIS_URL:       z.string().url().optional(),
  NEXTAUTH_SECRET: z.string().min(32),
  RAZORPAY_KEY_ID: z.string().startsWith('rzp_'),
  PORT:            z.coerce.number().int().positive().default(3000),
})

const parsed = EnvSchema.safeParse(process.env)
if (!parsed.success) {
  console.error('Invalid environment variables:')
  console.error(parsed.error.flatten().fieldErrors)
  process.exit(1)
}

export const env = parsed.data
// env.PORT is typed as number, env.DATABASE_URL is typed as string

Enter fullscreen mode Exit fullscreen mode

People Also Ask

What is the difference between parse and safeParse in Zod?

parse throws a ZodError if validation fails. Use it when you want the error to propagate up as an exception — common in server-side code where you have a top-level error handler. safeParse returns a discriminated union { success: true, data } | { success: false, error }. Use it when you need to handle validation failure gracefully without exceptions — typical for API request validation and form handling where you want to return structured error messages.

Can Zod schemas generate OpenAPI / JSON Schema documentation?

Yes, via the zod-to-json-schema package (npm install zod-to-json-schema). Call zodToJsonSchema(MySchema) to get a JSON Schema object you can plug into Swagger UI or any OpenAPI toolchain. For full OpenAPI 3.x spec generation, @asteasolutions/zod-to-openapi provides a registry-based API that produces complete path definitions including request bodies, query params, and response schemas.

How do I handle validation errors in a way that maps to form field errors?

Use error.flatten() on the ZodError. It returns { fieldErrors: Record<string, string[]>, formErrors: string[] }. Field errors are keyed by the field path (e.g., { email: ['Invalid email address'] }). If you are using React Hook Form with zodResolver, this mapping happens automatically — the resolver converts Zod errors into React Hook Form's error format and populates formState.errors for you.

Originally published at wowhow.cloud