Performance: Validating route params and query
This affects server response time and user experience by preventing unnecessary processing and errors early in the request lifecycle.
Jump into concepts and practice - no test required
import { param, query, validationResult } from 'express-validator'; app.get('/user/:id', [ param('id').isUUID(), query('verbose').optional().isBoolean() ], (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const id = req.params.id; database.findUserById(id).then(user => { if (!user) { res.status(404).send('User not found'); } else { res.json(user); } }); });
app.get('/user/:id', (req, res) => { const id = req.params.id; // No validation database.findUserById(id).then(user => { if (!user) { res.status(404).send('User not found'); } else { res.json(user); } }); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No validation before DB call | N/A (server-side) | N/A | N/A | [X] Bad |
| Validation middleware before DB call | N/A (server-side) | N/A | N/A | [OK] Good |
id in Express?req.params.id parameter, use req.params.id.app.get('/user/:id', (req, res) => {
const id = req.params.id;
if (!/^\d+$/.test(id)) {
return res.status(400).send('Invalid ID');
}
res.send(`User ID is ${id}`);
});/user/abc123?^\d+$ matches only digits from start to end.abc123 contains letters, so it fails the test.app.get('/search', (req, res) => {
const { term } = req.query;
if (!term || term.length < 3) {
res.status(400).send('Search term too short');
}
res.send(`Searching for ${term}`);
});term is missing or too short, it sends a 400 response.return after res.status(400).send(), so code continues and tries to send another response.userId (must be a number) and a query parameter active (must be 'true' or 'false') in Express. Which code snippet correctly validates both and returns 400 errors if invalid?^\d+$ on req.params.userId, correctly checking it is numeric string.active equals 'true' or 'false' strings, returning 400 if not.return after sending 400 responses, preventing multiple sends.