Easily Validate Your Node.js Inputs with Zod
Tags: zod, typescript, node, tutorial
Published: 2023-01-19 13:53:12

[![Substack Newsletter](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qbg4qlzlytxbzbvj97ia.png)](https://benoitpetit.substack.com/subscribe)

In this tutorial, we will explore how to use Zod, a TypeScript-first schema validation library, to validate inputs in our Node.js application. Zod uses static type inference to automatically generate validators from our TypeScript types, eliminating the need to manually write validation rules.

To start, we will install Zod using npm:
```shell
npm install zod
```

## Example Usage

In this example, we will validate an object containing information about a user. We will define a TypeScript type for this object and use Zod to generate a validator from this type.

```javascript
import * as z from 'zod'

interface User {
  name: string;
  age: number;
  email: string;
}

const userSchema = z.object({
  name: z.string().nonempty(),
  age: z.number().positive(),
  email: z.string().email()
});
```

Here, we have defined our user schema using Zod's string, number, and email validation methods. We can now use this validator to validate user objects:

```javascript
const validUser = { name: 'John Doe', age: 30, email: 'johndoe@example.com' };
const valid = userSchema.validate(validUser);
console.log(valid); // { name: 'John Doe', age: 30, email: 'johndoe@example.com' }

const invalidUser = { name: '', age: -5, email: 'notanemail' };
const error = userSchema.validate(invalidUser);
console.log(error); // { name: 'string must not be empty', age: 'number must be positive', email: 'string must be a valid email' }
```
## Integration with Node.js

To integrate Zod with our Node.js application, we can use the validator generated by Zod in an Express middleware to validate inputs in our API.

```javascript
import * as express from 'express';

const app = express();

app.use(express.json());

app.post('/users', (req, res) => {
  const { error, value } = userSchema.validate(req.body);

  if (error) {
    return res.status(400).send(error);
  }

  // Input is valid, we can continue processing the request
  // ...
});
```

## Conclusion

By using Zod, we can easily validate inputs in our Node.js application using TypeScript's static type inference. This allows us to define our validation schemas alongside our data model, eliminating the need to manually write validation rules. Additionally, using Zod can also improve the readability and maintainability of our code, as validation errors are clearly defined in the schema. Overall, Zod is a useful tool for any Node.js developer using TypeScript to ensure inputs in their application conform to specific validation rules.

---

> 🫶 If you appreciate my posts and would like to support my work, feel free to make a donation by clicking on the Stripe Sponsor link below or by scanning the QR code. [Stripe Link Sponsor](https://donate.stripe.com/00g6pJ6R19MJ15S7ss)

---

[![Stripe Sponsor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ohkf7lrymedkort4w9iz.png)](https://donate.stripe.com/00g6pJ6R19MJ15S7ss)

--- 

👀 See me here : 

- [Substack](https://benoitpetit.substack.com/subscribe)
- [Mastodon](https://piaille.fr/@codingben) 
- [(X) Twitter](https://twitter.com/codingben_)
- [Github](https://github.com/benoitpetit)
- [NPM Packages](https://www.npmjs.com/~codingben)
- [benoitpetit.dev](https://benoitpetit.dev)
- [Dev.to](https://dev.to/benoitpetit)