Basic presence validation on a POST login route
minimal input validation.
ensure the JSON body parser runs, destructure email and password from req.body, return 400 early if either is missing, then proceed.
WHAT THIS TESTS Whether you know that validation must happen server-side, that req.body requires a body parser, and that you must short-circuit on failure.
A GOOD ANSWER COVERS First, the application must mount express.json (or express.urlencoded) so the incoming JSON body is parsed into req.body; without it req.body is undefined and any access throws. In the route handler you destructure email and password from req.body and verify both are present and non-empty. If either is missing you immediately respond with status 400 and a descriptive error, and crucially you return so the rest of the handler does not run. Only after the guard passes do you proceed to look up the user and check credentials. This is a fail-fast pattern: reject malformed input at the boundary before doing real work. Client-side validation is a convenience, not a security control, so the server must validate independently.
COMMON WRONG ANSWERS Forgetting express.json so req.body is undefined, sending a 400 without returning so later code still executes, or trusting client-side checks alone.
LIKELY FOLLOW-UPS Why server-side validation is mandatory, moving validation into reusable middleware, using a schema library like Joi, and distinguishing missing from malformed input.
ONE CONCRETE EXAMPLE app.post('/login', (req, res) => { const { email, password } = req.body; if (!email || !password) { return res.status(400).json({ error: 'email and password are required' }); } /* proceed to authenticate */ }); The leading return ensures that when a field is missing, the response is sent once and the authentication code never executes with undefined values.
Read the original → expressjs.com
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.