If you have developed APIs before, you know one of the tiresome work is to write logic for validating the Data that is coming from frontend, like …
If the keys are available in request.body
Is it a valid number ..?
is the array containing a minimum of 1 element ..?
For example let’s see an example of traditional validation function for an API request
Traditional way of validating API requests
validateUser function might look like below
Validation Logic for user request body
The problems with this kind of validation is that it is
— Not reusable
— Changes often based on the nature of API
— Prone to error
— Every developer will have their own validation logic
— Mainly, if I change something here at backend part, I need to make sure frontend adheres to it, There is not strict contract between frontend and backend.
Zod is a modern schema validation library for typescript which exactly solves the above addressed problems, it supports all the types that you might use on a day to day basis and also has support for constructing complex types. Apart from schema validation it also supports static type inference & Error handling out of the box. This blog has two parts, in this section we’ll go through the basic usage of Zod and in second part we’ll discuss Zod customizations for our own use case.
Let’s look at the same create_user example, but with the power of Zod
First we need to create a schema for the user
then we just need to use the schema to parse the request body we using .safeParse() which will return either success or error for further processing
Looks simple right , but it’s powerful, now you can reuse it wherever you want , either inside the same codebase or in a shared repository because it comes with zero dependencies. Let’s discuss the Pragmatic way of error handling, tricks and tips in part 2.