How many times has this happened to you?
You're writing a super sweet api that consumes some data from a database and tosses that data to some front-end where it can be consumed by users.
Maybe your api has a POST endpoint where users can upload data that's being consumed and viewed by other users. That's all fine and dandy until you start to get some bad data into your database. Maybe some data that doesn't fit a model and will blow up your application if not formatted properly.
See, Typescript is awesome in all, but it lacks data security. It might tell you (the developer) that a type is missing a property but it wouldn't actually stop data from going through that part of your application.
This is where Zod comes in.
Zod is an amazing library. You can use it to define schema's, create types, and most importantly... validate data. This data validation library was created to fill in the gaps that Typescript leaves behind.
That sounds great in all... but how about some examples?
Defining a schema:
Here we create a schema called "POST_SCHEMA", it expects some data to have an id with a length of 16, a postNumber that's a number, and a few more fields. You get the idea.
Inferring a Type:
We can now create a type from our schema to use anywhere else in our app.
This looks and will act the same as:
But the benefit is we also have a schema to validate our data.
Parsing data:
Now that we have a schema, we can validate or "parse" our data to make sure it fits our defined model.
Zod will throw an error if the data isn't matching the schema we created.
But what if I don't want to throw an error?
That's easy, we can just use the safeParse
function instead!
If you're curious about this library, you can view the full documentation here. It's helped me a lot on production projects and hopefully it helps you too.
Thanks for reading!
Top comments (0)