zahid ansari
Building scalable systems by applying mental models to code and architecture.
Website
Install this app to stay connected and in the loop.
Building meaningful experiences one pixel at a time 😉.
Made with by Zahid
views
zahid ansari
Building scalable systems by applying mental models to code and architecture.
Website
Install this app to stay connected and in the loop.
Building meaningful experiences one pixel at a time 😉.
Made with by Zahid
views

Share
API contracts are critical for scalability. Learn how Zod validation + TypeScript ensures your API is bulletproof and catches errors before production.
Building APIs in Next.js without type safety is like debugging in the dark. You assume the data is correct, but one missing field crashes your app.
I was working on a user update feature where the frontend sent a slightly different payload than the backend expected. Result? Silent failures and hours of debugging. I needed a way to guarantee that incoming data matched exactly what my code expected, instantly.
Zod is a TypeScript-first schema declaration and validation library. It allows you to verify data at runtime (when the API is hit) while giving you static type inference during development.
1import { z } from "zod";
2
3const updateUserSchema = z.object({
4 id: z.string().uuid(),
5 email: z.string().email(),
6 role: z.enum(["admin", "user", "guest"]),
7 preferences: z.object({
8 theme: z.enum(["light", "dark"]),
9 notifications: z.boolean(),
10 }),
11});
12
13// Infer TypeScript type automatically
14type UpdateUserBody = z.infer<typeof updateUserSchema>;1import { NextResponse } from "next/server";
2
3export async function POST(request: Request) {
4 try {
5 const body = await request.json();
6
7 // Validate request body
8 const result = updateUserSchema.safeParse(body);
9
10 if (!result.success) {
11 return NextResponse.json(
12 { error: "Invalid data", details: result.error.format() },
13 { status: 400 }
14 );
15 }
16
17 const { email, role } = result.data;
18 // Proceed with database update reliably...
19
20 return NextResponse.json({ success: true, email });
21
22 } catch (error) {
23 return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
24 }
25}Mistake 1: Trusting frontend validation only.
Mistake 2: Manually defining interfaces that drift from validation logic.
1z.infer<typeof schema>1schema/qwBy adding Zod, we turned runtime uncertainty into compile-time confidence. It makes refactoring easier and catches bugs before they even hit the database.
Tech Stack: Next.js, Zod, TypeScript