Facebook Pixel

How do I validate URL params with Zod in Express?

Same pattern, but validate req.params. Example: const idSchema = z.object({ id: z.string().length(24) }); router.get('/users/:id', validateParams(idSchema), getUser). Use a separate factory that reads req.params.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in How to Write an Express Validation Middleware With Zod

Define a Zod schema, write a validate(schema) middleware factory that uses safeParse, returns 400 with errors if invalid, replaces req.body with parsed data if valid, and calls next. Apply per route: router.post('/signup', validate(signupSchema), signup).

TypeScript inference, great error messages, composable schemas, safe parse (returns success or error instead of throwing), and built-in types. It is one of the best modern validators for Node.js.

Returns an object with success: true and data, or success: false and error. Unlike parse, it does not throw. This is what you want in a middleware, where you want to handle errors gracefully instead of catching throws.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.