Skip to content

Instantly share code, notes, and snippets.

@SwiftedMind
Created November 11, 2023 17:29
Show Gist options
  • Save SwiftedMind/d15a8a7d0a4d8441fb3b11be25f24a0f to your computer and use it in GitHub Desktop.
Save SwiftedMind/d15a8a7d0a4d8441fb3b11be25f24a0f to your computer and use it in GitHub Desktop.
Request Validation in Next.js
import { ZodError, z } from "zod";
interface RequestBody {
name: string;
}
const RequestBody = z.object({
name: z.string(),
});
export async function POST(request: Request) {
try {
const body = RequestBody.parse(await request.json());
return Response.json({ message: body.name });
} catch (error) {
if (error instanceof ZodError) {
console.log(error);
return new Response("Invalid Data", { status: 400 });
} else {
return new Response("Bad Request", { status: 400 });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment