Simplifying Input Validation in Node.js with Zod
Tags: beginners, node, express, zod
Published: 2024-04-07 07:38:50

As developers, ensuring that the data flowing into our applications is accurate and well-structured is paramount. One small error in input validation can lead to significant issues down the line, compromising security and stability. Thankfully, with tools like Zod, handling input validation in Node.js applications has never been easier.

### Why Input Validation Matters
Let's assume, instead of sending the username and the password a user sends some random data and tries to crash the server. It is our (Software Engineer) responsibility to check the data is in the proper format.

### Introducing Zod
Zod is a powerful JavaScript and TypeScript library that simplifies the process of defining data schemas and validating them at runtime. With Zod, developers can effortlessly define blueprints for their data, making input validation a breeze.

### Install Zod: Start by installing Zod via npm using the command
`npm install zod`
### Import Zod:
`cosnt {z} = require('zod');`

####Creating Schemas with Zod
Zod allows developers to create schemas that define the structure and constraints of their data. Let's take a look at how we can define schemas using Zod:

```
const usernameSchema = z.string()
const phoneSchema = z.number()

//we can create the object also

const user = z.object({
	username : z.string().min(5), //username will be a string with a min of 5 char
	email:z.email(), //email should be email
	firstname:z.sting().max(5) //first name will be string, and length should not exceed 5 char
})
```
### Let's see a few more primitive schemas.

```
// primitive values
z.string();
z.number();
z.bigint();
z.boolean();
z.date();

// empty types
z.undefined();
z.null();
```
### Validating Inputs
Once we've defined our schemas, Zod provides convenient methods for validating input data:

```


const {z} = require('zod');

//create the schema

const userSchema = z.object({
	firstname : z.string().min(5),
	lastname : z.string().min(5),
	email:z.email();
	password :z.string()
})

//parse the Shema

try{
	userSchema.safeparse({
		firstname: "Tirth",
		lastname:"Raval",
		email:"tirth.b.raval@gmail.com"
		password:"titrh@1234"
	})
}
catch (error){
	console.log("error ${error}")
}

```
Using safeParse, we can validate input data against our schema and handle any validation errors that may occur.

### Integrating Zod with Express.js

```
const express = require('express');
const zod = require('zod');
const app = express();


app.use(express.json());
const useInputValidation = (req,res,next) => {
    const input  = req.query.Kidneys;
    const inputSchema = zod.string();
    // console.log(typeof(input))
    if(!inputSchema.safeParse(input).success){
        
        res.status(400).json({
            msg:"Input are wrong"
        })
        return;
    }
    else{
       next();
    }

}
app.get('/health-chek', useInputValidation, (req,res)=>{

    res.json({
        msg :"You are find"
    })

});

app.listen(3000);

```
In this example, we've created a middleware function userInputValidation to validate incoming data before processing it further. If the input fails validation, we return a 400 Bad Request response with an error message.

### Conclusion
Zod simplifies input validation in Node.js applications, providing a robust solution for ensuring data integrity and security. Developers can build more reliable, maintainable, and secure applications by defining clear schemas and leveraging Zod's validation capabilities. Whether you're working on a small personal project or a large-scale enterprise application, Zod has you covered when it comes to input validation in Node.js.

Start using Zod today and streamline your input validation process like never before!

Thank you!!