Frontend Blocks typescript Intermediate

Next.js API Route with Zod Validation

Type-safe Next.js API route that validates the request body with Zod.

typescript
import type { NextApiRequest, NextApiResponse } from 'next';
import { z } from 'zod';
const schema = z.object({ email: z.string().email(), amount: z.number().int().min(1) });
export default function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== 'POST') return res.status(405).end();
  const parsed = schema.safeParse(req.body);
  if (!parsed.success) return res.status(422).json({ errors: parsed.error.flatten().fieldErrors });
  return res.status(200).json({ ok: true });
}

Prerequisites

  • next.js >= 13
  • zod

Pro Tips

  • → Extract schema to shared folder for client+server reuse.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
typescript
Level
Intermediate
Read time
3 min
Published
Oct 2024
License
Commercial License

Newsletter

New modules every week, directly to your inbox.