Last active
November 23, 2023 02:15
-
-
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)
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
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