Zod is a library for validating data with awesome support for Typescript. Learn how to use it within your NextKit project.
Zod is a Typescript library that helps us secure our API endpoints by validating the payloads sent from the client and also facilitating the typing of the payloads with Typescript.
Using Zod is the first line of defense to validate the data sent against our API: as a result, it's something we recommend you keep doing. It ensures we write safe, resilient, and valid code.
All NextKit's API routes are secured with Zod: in this document, we want to explain the conventions used by the SaaS Boilerplate, and how to use it for your API endpoints.
When we write an API endpoint or a Server Action, we first define the schema of the payload:
This function represents the schema, which will validate the following interface:
Now, let's write the body of a Server Action that validates the body of the function, which we expect to be equal to the Body interface.
You can also use safeParse if you prefer not to throw an error when the validation fails: