Skip to content

Instantly share code, notes, and snippets.

@aryanprince
Last active November 23, 2023 02:15
Show Gist options
  • Save aryanprince/a2e297114b5a24f39274b8cc78547875 to your computer and use it in GitHub Desktop.
Save aryanprince/a2e297114b5a24f39274b8cc78547875 to your computer and use it in GitHub Desktop.
How to validate POST request body using `zod` to ensure typesafety (for pages router API endpoints)
const createUserRequestSchema = z.object({
name: z.string(),
email: z.string().email(),
})
type CreateUserRequestBody = z.infer<typeof createUserRequestSchema>
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method === 'POST') {
let requestBody: CreateUserRequestBody
try {
requestBody = createUserRequestSchema.parse(req.body)
} catch (error) {
if (error instanceof ZodError) {
return res.status(400).json({ error: error.message })
}
return res.status(400).json({ error: 'Invalid types provided in request body' })
}
const { name, email } = requestBody;
// Prisma code here
// prisma.create(name, email, etc)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment