Created
November 11, 2023 17:29
-
-
Save SwiftedMind/d15a8a7d0a4d8441fb3b11be25f24a0f to your computer and use it in GitHub Desktop.
Request Validation in Next.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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