Zod

Zod Is Your Friend

Ethan Glover

8,707,674 weekly NPM downloads. Over 3,000 dependent libraries. Built in support with most React form libraries, QwikJS, tRPC, and a healthy amount of funding. What is the value of Zod? TypeScript itself can create a strong level of type safety. But it doesn't protect you from runtime type bugs. If it isn't used properly, it can provide effectively zero type safety on the edges of your application. Misused, TypeScript will do more harm than good.

For example, to get the number of downloads for Zod I make a fetch call to the NPM registry:

1const zodDownloadsResponse = await fetch(

To get the response data you need to parse the JSON from the Response object.

1const zodDownloadsData = await zodDownloadsResponse.json()

There should be a glaring issue with this. zodDownloadsData is now implicitly typed as ‘any’. People new to TypeScript might solve this problem by casting it to a type.

1type ZodDownloads = {

This is a terrible mistake. It gives the developer the illusion of type safety and doesn't make use of TypeScript at all. This is effectively the same as using JSDocs comments. It provides no type safety, it is only for in-editor documentation. The point of TypeScript is not to create handy autocompletes that reassure you everything is OK, it is to help you create a type safe application.

Shotgun parsing is a programming antipattern whereby parsing and input-validating code is mixed with and spread across processing code—throwing a cloud of checks at the input, and hoping, without any systematic justification, that one or another would catch all the “bad” cases.

- Parse, don’t validate

TL;DR

Zod provides a functional approach to parsing data without being purist or dogmatic about functional programming. Never assume you're getting the correct data from an external system. Check it first.

1const zodDownloadsSchema = z.object({

Inputs and Outputs

Zod goes beyond simple types because it is making runtime checks, we can add any parsing logic we want. For example I have a “createBlog” function:

1const createBlog = (

First thing, I'm letting this function throw. Mostly because it runs for every blog at build time. I'm OK with letting the build fail on error. But also notice the ‘z. input ’ and ‘z. output ’ for the parameter and return types. The schema looks like this:

1export const createBlogSchema = z

The defaults and transformations help create two different types. The input types equivalent looks like this:

1type CreateBlogInput = {

Notice there is no _id, and authors and timezone are both optional due to the fact that they have default values. The equivalent output type will look like this:

1type CreateBlogOutput = {

Now _id is included and all fields are required. Two types for the price of one! We know exactly what we can pass in and exactly what we'll get back. And we know this for sure because of the runtime parsing.

Of course as a last note, the triviality of this function makes getting both input and output types from a single Zod schema possible. This is basically treating Zod as a class constructor. Which is entirely valid. But maybe not the usual use case.

Forms

React Hook Formis just one example of a form library with built in support for validation. This provides an easy way to create complex validations for forms without lengthy if/else conditions and checks within a submit function.

A sign up form may use a schema like this:

1const nameSchema = z.string().min(3).max(100);

This gives us a pretty straightforward and quickly readable definition of this forms rules. names need to be between 3 and 100 characters. We have built-in email validation. A regex test for the password. And a final refine to make sure the password and confirmPassword are equal.

When using react hook form, all you have to do is include the ZodSchema as a “resolver” and it will run before the form onSubmit.

1const { formState: { errors } } = useForm({

Go ahead and give it a try.

API's

tRPC makes beautiful use of Zod by baking it into the framework itself. I used tRPC and Zod as a great example of how to separate parsing from API logic for testability. For the tl;dr, tRPC provides a clean interface to parse and validate all incoming and outgoing data from your API:

1export const create = procedure

But of course because Zod is a standalone library it works fine anywhere with TypeScript. Just create a schema and parse it. Handle errors with the previously mentioned try/catch or functional safeParse.

Testing

Again, Zod as a tool for testing is largely covered in the previously mentioned “Making React Testable” . With @anatine/zod-mock it's very easy to mock data from Zod schemas. Using faker.js as a dependency this library will do it automatically. Using tools like Zod and it's supporting libraries will quickly help you find a path towards better unit testing. Many developers struggle to really understand separation of concerns. Doing “stream of consciousness coding” creates bad tests whether you prescribe to any tribe like TDD or BDD or none at all. These frameworks won't help you if you don't split up your code.

Learning to separate parsing from logic means smaller, more concise, and more accurate tests. With each piece easier to test in full. Schema can be tested with correct error handling and logic can be tested given variations of that schemas parsed output. Mixing parsing and logic eventually leads to missed tests due to the fact that the code ran and we long longer see the misstep in coverage reports.

1it('should validate correct input', () => {

Environment Variables

As a bonus, and a testament to the flexibility of Zod. For every project, I always include a .environment.ts file which reads process.env. If for example, you have a OPENAI_KEY variable, the type of process.env.OPENAI_KEY is ‘string | undefined’. If all of your environment variables are defined, this isn't true. It should be ‘string’. Nor does this help you determine what is and isn't defined when it is defined. In other words, process.env has to be shotgun parsed. So we can simply parse it with Zod.

1const environmentSchema = z.object({

This conveniently forces environment variables to be checked when the app is started or during build. If something is missing, it throws and we get a helpful reminder to make sure to define all required environment variables.