Validating request bodies with Express middleware
separating validation from business logic via middleware.
run validation middleware before the handler, check email format and password length, return 400 with errors on failure, call next on success.
WHAT THIS TESTS Whether the candidate structures Express applications cleanly by isolating cross-cutting concerns like validation into middleware, and understands the request-response pipeline.
A GOOD ANSWER COVERS Express processes a request through an ordered chain of middleware. Validation belongs in a middleware that runs before the route handler, so the handler can assume clean input. Using express-validator, you declare checks such as body('email').isEmail() and body('password').isLength({ min: 8 }), then a small middleware reads validationResult(req); if there are errors it responds with status 400 and a JSON array describing each failure, otherwise it calls next() to pass control to the handler. The same pattern works with a schema library like Joi or Zod, validating req.body against a schema. Server-side validation is mandatory regardless of any client-side checks, because clients can be bypassed.
COMMON WRONG ANSWERS Putting validation logic inside the route handler, which couples concerns and duplicates code across routes. Trusting client-side validation as sufficient. Forgetting to short-circuit with a 400 and instead continuing to the handler. Returning a 200 or 500 for what is a client input error rather than the correct 400 or 422.
LIKELY FOLLOW-UPS How do you avoid leaking which field failed in a security-sensitive flow? Where do you centralize error formatting? How do you reuse the same schema on multiple routes? How do you handle async validation like uniqueness checks against the database?
ONE CONCRETE EXAMPLE A POST /users route is registered as router.post('/users', validateUser, createUser). validateUser runs the email and password checks; on a missing or malformed email it returns 400 with a body like { errors: [{ field: 'email', message: 'Invalid email' }] }, and createUser never executes. On valid input it calls next() and the handler hashes the password and persists the user.
Read the original → express-validator.github.io
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.