How do I validate input in an Express router?
Use a validate(schema) middleware factory that uses Zod's safeParse. Apply per route: router.post('/', validate(createPostSchema), createPost). Returns 400 with errors if invalid, replaces req.body with parsed data if valid.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Writing REST APIs With Express Router: A Complete Walkthrough
Define a Mongoose schema, write a controller with asyncHandler and ApiError, write a router with auth and validation middlewares, mount the router in app.js, and write Zod validation schemas. Each file has one job; the router stays thin.
Parse the request, call a model or service, send the response with the right status code, and handle errors with ApiError. Check resource ownership for user-specific resources. Use asyncHandler so rejections go to the error handler.
Load the resource, compare its owner to req.user.userId. If they do not match and the user is not an admin, throw new ApiError(403, 'Not authorized'). Do this before updating or deleting.
Still have questions?
Browse all our FAQs or reach out to our support team
