Zod
TypeScript-first Schema Validation
A TypeScript-first schema validation library. Provides runtime validation and static type inference at the same time, supporting type-safe application development.
TypeScript-first Schema Validation
A TypeScript-first schema validation library. Provides runtime validation and static type inference at the same time, supporting type-safe application development.
Zod is a schema declaration and validation library designed for TypeScript. Once you define a schema, you get both runtime data validation and TypeScript type inference at the same time, so there is no need to write type definitions twice. Following the "DRY (Don't Repeat Yourself)" principle while still guaranteeing complete type safety is Zod's core philosophy.
Zod's greatest strength is the seamless integration of type inference and runtime validation. TypeScript's type system works only at compile time, so it cannot validate data coming in from outside (API responses, user input, environment variables, etc.). Zod bridges this gap: the structure defined by a schema is validated at runtime and also inferred as a TypeScript type at the same time. Using z.infer, you can automatically extract a type from a schema.
Compared with other validation libraries such as Yup and Joi, Zod stands out in TypeScript friendliness. Yup appeared earlier in the JavaScript ecosystem and had type support added later, while Joi is optimized for Node.js environments and has a large browser bundle size. Zod, on the other hand, was designed for TypeScript from the start, so type inference is natural, it has no dependencies (zero dependencies) so tree shaking is efficient, and its bundle size is small as well.
In practice, Zod is used in a variety of areas. It is integrated with React Hook Form, Formik, and others for form validation, and combined with tRPC to build end-to-end type-safe APIs. It also ensures runtime safety in API response validation, environment variable parsing, configuration file validation, and more. In full-stack frameworks such as Next.js and Remix, it has become the standard for data validation between server and client.
// 1. 기본 스키마 정의
import { z } from 'zod';
// 원시 타입 스키마
const stringSchema = z.string();
const numberSchema = z.number().positive().int();
const booleanSchema = z.boolean();
// 객체 스키마 정의
const UserSchema = z.object({
id: z.number(),
name: z.string().min(2, '이름은 2자 이상이어야 합니다'),
email: z.string().email('올바른 이메일 형식이 아닙니다'),
age: z.number().min(0).max(150).optional(),
role: z.enum(['admin', 'user', 'guest']),
createdAt: z.date().default(() => new Date()),
});
// 2. 타입 추론 - 스키마에서 TypeScript 타입 자동 추출
type User = z.infer<typeof UserSchema>;
// 결과: { id: number; name: string; email: string; age?: number; role: 'admin' | 'user' | 'guest'; createdAt: Date; }
// 3. 데이터 검증 (parse vs safeParse)
const userData = {
id: 1,
name: '김개발',
email: 'dev@example.com',
role: 'user'
};
// parse - 실패 시 예외 발생
try {
const user = UserSchema.parse(userData);
console.log('검증 성공:', user.name);
} catch (error) {
if (error instanceof z.ZodError) {
console.error('검증 실패:', error.errors);
}
}
// safeParse - 결과를 객체로 반환 (권장)
const result = UserSchema.safeParse(userData);
if (result.success) {
console.log('사용자:', result.data.email);
} else {
console.error('오류:', result.error.flatten());
}
// 4. 고급 스키마 패턴
// API 응답 스키마
const ApiResponseSchema = <T extends z.ZodTypeAny>(dataSchema: T) =>
z.object({
success: z.boolean(),
data: dataSchema,
message: z.string().optional(),
timestamp: z.string().datetime(),
});
const UserListResponse = ApiResponseSchema(z.array(UserSchema));
type UserListResponse = z.infer<typeof UserListResponse>;
// 5. 폼 검증 (React Hook Form 연동)
const LoginFormSchema = z.object({
email: z.string().email('올바른 이메일을 입력하세요'),
password: z.string()
.min(8, '비밀번호는 8자 이상이어야 합니다')
.regex(/[A-Z]/, '대문자를 포함해야 합니다')
.regex(/[0-9]/, '숫자를 포함해야 합니다'),
rememberMe: z.boolean().default(false),
});
// 6. 변환(transform)과 정제(refine)
const ProductSchema = z.object({
name: z.string().transform(s => s.trim()),
price: z.string().transform(Number).pipe(z.number().positive()),
quantity: z.coerce.number().int().min(1),
}).refine(
data => data.quantity <= 100,
{ message: '한 번에 100개까지만 주문 가능합니다' }
);
"We keep getting runtime errors because we take external API responses as any and use them directly. How about introducing Zod schemas to validate API responses? We'd validate with safeParse, and on failure, report the error and return fallback data. Once we define the schema, the types come out automatically, so there's no duplicate type definition either."
"This form schema design is good, but the check that password and confirmPassword match should be done at the object level with refine, not at each field level. Also, please add the path option to the error message so it's clear which field the error is for. Using flatten() makes it much easier to display errors on the frontend."
"I've used Yup too, but I prefer Zod. Yup's type inference isn't perfect, so I often had to use as Type casting. With Zod, types are fully inferred from the schema via z.infer, and combined with tRPC you get end-to-end type safety between client and server, which makes it ideal for full-stack TypeScript projects."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Zod is relatively small at about 12KB (gzipped), but consider its impact when it is included in the client bundle. If you only need server-side validation, you can exclude it from the client bundle and use lightweight validation logic on the client instead. Since it tree-shakes well, import only the features you use.
The default error messages may not be user-friendly. Specify Korean messages explicitly for each validation rule, or set a global error map with z.setErrorMap(). If you need multilingual support, you can integrate with an i18n library to generate messages dynamically.
Performance issues can occur when validating large arrays or deeply nested objects. For repeated validation, create the schema in advance and reuse it. For real-time input validation, apply debounce, and using a partial schema that validates only the necessary fields can improve performance.