Go back
Zod
TypeScriptZodWeb Development

Getting Started with Zod

A beginner friendly guide to validating data in TypeScript using Zod’s powerful schema system—making your apps safer, cleaner, and more predictable.

July 23, 2024

Zod is a TypeScript-first schema declaration and validation library. What does this mean? It means that you can create schemas that are type-safe while also providing validation. When you validate data against a Zod schema, it not only checks the data’s structure but also returns a typed object that TypeScript can understand. This ensures that your data conforms to the expected types and improves overall code reliability.

You might have noticed that I used the word “schema” multiple times. It broadly refers to any data type, from a simple number to a complex nested object.

Schemas

To better understand how schemas work, let’s create a simple schema using Zod.

typescript
1import { z } from 'zod'
2
3const stringSchema = z.string()
4
5stringSchema.parse('zod') // returns 'zod' since it is a string
6stringSchema.parse(12) // throws an error

Zod also provides a way to coerce values:

typescript
1import { z } from 'zod'
2
3const stringSchema = z.coerce.string()
4
5stringSchema.parse(12) // coerces and returns '12'

Let’s take a real world example and create a schema for the sign up form.

typescript
1import { z } from 'zod'
2
3export const signUpSchema = z.object({
4  username: z.string().min(3).max(20),
5  email: z.email(),
6  password: z.string().min(6),
7})

You can even add customized error messages to your schema.

typescript
1export const signUpSchema = z.object({
2  username: z
3    .string()
4    .min(3, "Username must have 3 characters")
5    .max(20, "Username cannot exceed 20 characters"),
6  email: z.email(),
7  password: z.string().min(6),
8})

Learn more about Zod:

Installation

Primitives

The most commonly used data types are string and number. Here is a link to Zod’s guide to a handful of validations for each of them.

Strings

Numbers