Zod Validation in Next.js with TypeScript

Zod is a powerful TypeScript-first schema validation library. In this blog, you'll learn how to install Zod and use it for validating data in your Next.js + TypeScript projects.

Watch the Tutorial

1. Install Zod

First, install Zod using npm or yarn:

npm install zod

If you are setting up TypeScript for your Node.js project, use:

npm install --save-dev typescript @types/node ts-node nodemon

2. Basic Usage Example

Here's how you can use Zod to validate an object:

Basic Usage Example
1import { z } from "zod"; 2 3const userSchema = z.object({ 4name: z.string(), 5age: z.number().min(18), 6}); 7 8const result = userSchema.safeParse({ name: "Avinash", age: 22 }); 9 10if (result.success) { 11// Valid data 12console.log(result.data); 13} else { 14// Validation errors 15console.error(result.error); 16}

3. Using Zod in Next.js API Route

You can use Zod to validate request bodies in your API routes:

API Route Example
1// pages/api/register.ts 2import { z } from "zod"; 3 4const registerSchema = z.object({ 5email: z.string().email(), 6password: z.string().min(6), 7}); 8 9export default function handler(req, res) { 10const result = registerSchema.safeParse(req.body); 11if (!result.success) { 12 return res.status(400).json({ error: result.error.errors }); 13} 14// Proceed with registration 15res.status(200).json({ message: "Registered!" }); 16}

4. Type Inference with Zod

Zod can infer TypeScript types from your schemas:

Type Inference
1const userSchema = z.object({ 2name: z.string(), 3age: z.number(), 4}); 5 6type User = z.infer<typeof userSchema>;

5. Why Zod?

  • TypeScript-first: Types are inferred automatically
  • Fast and lightweight
  • Great error messages
  • Works perfectly with Next.js

TypeScript Configuration Example

tsconfig.json
1{ 2 "compilerOptions": { 3 "target": "ES2020", 4 "module": "commonjs", 5 "outDir": "dist", 6 "rootDir": "src", 7 "strict": true, 8 "esModuleInterop": true 9 } 10}

Zod makes validation in TypeScript projects easy and reliable. Try it in your Next.js app today!

Logo

I'm Avinash - a full-stack developer, freelancer & problem solver. Thanks for checking out iBlogs!

Platforms
YouTube