Performance: Sanitization methods
Sanitization methods affect input processing speed and server response time by adding validation and cleaning steps before data handling.
Jump into concepts and practice - no test required
import { body } from 'express-validator'; app.post('/submit', [ body('input').escape() ], (req, res) => { const sanitized = req.body.input; res.send(`Received: ${sanitized}`); });
app.post('/submit', (req, res) => { const userInput = req.body.input; // Manual string replace for sanitization const sanitized = userInput.replace(/<script.*?>.*?<\/script>/gi, ''); // Proceed with sanitized input res.send(`Received: ${sanitized}`); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual regex sanitization on server input | N/A | N/A | N/A | [X] Bad |
| Using express-validator sanitize middleware | N/A | N/A | N/A | [OK] Good |
trim() method removes spaces from the start and end of a string.escape() converts special characters, normalizeEmail() formats emails, toLowerCase() changes case.const { body, validationResult } = require('express-validator');
app.post('/submit', [
body('email').normalizeEmail(),
body('username').trim().escape()
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send({ email: req.body.email, username: req.body.username });
});{ email: ' USER@Example.COM ', username: ' John ' }app.post('/data', (req, res) => {
req.body.name = req.body.name.trim.escape();
res.send(req.body.name);
});email, username, and bio. Which combination of sanitization methods is best to ensure safe and clean data?normalizeEmail() formats and cleans email addresses correctly.trim() removes extra spaces, escape() prevents harmful HTML or scripts in username and bio.normalizeEmail() for email, trim() and escape() for username, and escape() for bio [OK]