Zod
Validate inputs in APIs.
pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import z from 'zod';
type Data = {
success: boolean;
error?: string;
data?: any;
};
const inputSchema = z.object({
email: z.string(),
});
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
try {
const { email } = inputSchema.parse({ email: req.query.email });
// you can be sure that 'email' is a string from here...
res.status(200).json({ success: true });
} catch (error: any) {
return res.status(500).json({ success: false, error });
}
}
Powerful validation options
const SUBSCRIPTIONS = ["HOBBY", "SCALER", "TEAM", "ENTERPRISE"] as const;
const SubscriptionEnum = z.enum(SUBSCRIPTIONS);
z.object({
title: z.string().min(5),
description: z.string().nullable(),
countViews: z.number(),
subscription: z.enum(SubscriptionEnum),
tags: z
.object({
value: z.string(),
label: z.string(),
color: z.string(),
})
.array(),
});