Back to articles
Zod Validation Patterns for Next.js: API Routes, Forms, and External APIs

Zod Validation Patterns for Next.js: API Routes, Forms, and External APIs

via Dev.toAtlas Whoff

The Zod Pattern Every Next.js App Needs Runtime validation is the gap between TypeScript's compile-time guarantees and what actually arrives at your API. User input, external APIs, and database queries can all return unexpected shapes. Zod closes that gap. Basic Schema Validation import { z } from ' zod ' const CreateUserSchema = z . object ({ name : z . string (). min ( 1 , ' Name is required ' ). max ( 100 ), email : z . string (). email ( ' Invalid email address ' ), age : z . number (). int (). min ( 18 , ' Must be 18+ ' ). max ( 120 ). optional (), role : z . enum ([ ' user ' , ' admin ' , ' moderator ' ]). default ( ' user ' ), }) // Infer TypeScript type from schema type CreateUser = z . infer < typeof CreateUserSchema > // Validate (throws on invalid) const user = CreateUserSchema . parse ( requestBody ) // Validate (returns result object, doesn't throw) const result = CreateUserSchema . safeParse ( requestBody ) if ( ! result . success ) { console . log ( result . error . issu

Continue reading on Dev.to

Opens in a new tab

Read Full Article
0 views

Related Articles