Tillitsdone
down Scroll to discover

Validate API Requests with Zod in Node.js

Learn how to implement robust API request validation in Node.js using Zod.

Discover type-safe schema validation, custom validation rules, and best practices for building secure APIs.
thumbnail

How to Validate API Request Bodies with Zod in Node.js

A floating geometric abstract shape representing data validation featuring interconnected hexagons and flowing lines in natural earthy tones of sage green and warm brown camera angle: straight on ultra-realistic cinematic lighting 8K UHD high resolution sharp and detailed

In the world of Node.js API development, ensuring the integrity and correctness of incoming data is crucial. Enter Zod - a TypeScript-first schema validation library that’s changing the game for input validation. Let’s dive into how you can leverage Zod to create rock-solid API endpoints.

Why Zod?

Traditional validation methods often feel clunky and verbose. Zod brings a fresh approach with its intuitive API and robust type inference. Unlike other validation libraries, Zod provides seamless TypeScript integration and runtime type checking, making it a powerful choice for modern Node.js applications.

Abstract fluid motion capturing the concept of data transformation with smooth flowing liquid-like shapes in iridescent silver and stone blue tones camera angle: top-down aerial view high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Getting Started

First, let’s set up our project with the necessary dependencies:

Terminal window
npm install zod express

Now, let’s create a simple Express server with Zod validation:

import express from 'express';
import { z } from 'zod';
const app = express();
app.use(express.json());
// Define our schema
const UserSchema = z.object({
username: z.string().min(3).max(50),
email: z.string().email(),
age: z.number().min(18).optional(),
});
app.post('/users', (req, res) => {
try {
const validatedData = UserSchema.parse(req.body);
// Process the validated data
res.json({ success: true, data: validatedData });
} catch (error) {
res.status(400).json({ error: error.errors });
}
});

Advanced Validation Patterns

Geometric crystal formations representing data structures with sharp angular shapes in seaweed green and bright turquoise colors camera angle: low angle perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Zod really shines when handling complex validation scenarios. Here are some powerful patterns:

// Nested object validation
const AddressSchema = z.object({
street: z.string(),
city: z.string(),
country: z.string(),
postalCode: z.string(),
});
const UserProfileSchema = z.object({
personal: z.object({
firstName: z.string(),
lastName: z.string(),
}),
addresses: z.array(AddressSchema),
preferences: z.record(z.string()),
});
// Custom validation
const PasswordSchema = z.string()
.min(8)
.refine(
(password) => /[A-Z]/.test(password),
'Password must contain at least one uppercase letter'
)
.refine(
(password) => /[0-9]/.test(password),
'Password must contain at least one number'
);

Best Practices

  1. Middleware Approach: Create reusable validation middleware for common patterns.
  2. Error Handling: Implement consistent error responses across your API.
  3. Schema Reusability: Define schemas separately and compose them as needed.

Here’s a practical example of validation middleware:

const validateRequest = (schema: z.ZodSchema) => {
return async (req: Request, res: Response, next: NextFunction) => {
try {
req.body = await schema.parseAsync(req.body);
next();
} catch (error) {
res.status(400).json({
error: {
message: 'Validation failed',
details: error.errors,
},
});
}
};
};
// Usage
app.post('/users', validateRequest(UserSchema), (req, res) => {
// Your route handler logic here
});

Conclusion

Zod provides a powerful, type-safe way to validate your API requests in Node.js. Its declarative syntax and rich feature set make it an excellent choice for building robust APIs. Start implementing Zod in your projects today, and you’ll wonder how you ever lived without it.

Abstract network of connected nodes representing data flow with dynamic lines and patterns in maroon and bright amber colors camera angle: dutch angle (tilted) high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

icons/logo-tid.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.