Skip to main content

Data Validation: Zod

Zod Logo

Zod is a TypeScript-first schema validation for your data. It follows a functional parsing approach rather than an imperative validation, which gives you static typing for your data without effort. It can be used to validate anything, including forms in the browser, and user input submissions on the server.

Might change soon?
Possibly

Setup

yarn add zod
import * as z from 'zod'

const objInput = { name: 'Toto' }

const objSchema = z.object({
  name: z.string(),
  age: z.number().optional(),
})

const objParsed = objSchema.parse(objInput)

// If you write "objParsed." in your editor, it will suggest "name" or "age".

Alternatives

Yup and Joi are the main alternatives, and they provide more validation patterns than Zod, but without the parsing approach that Zod offers (although it may catch up). The comfort of TypeScript types has an edge over those in my opinion.