🟢 Node.js Intermediate

What is input validation and sanitization in Node.js?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

Answer

Input validation ensures incoming data meets expected rules (required fields, correct types, valid formats) before processing. Sanitization cleans input by removing or escaping dangerous characters to prevent injection attacks. Both are essential security layers at API boundaries. Libraries: (1) Joi — powerful schema-based validation: const schema = Joi.object({ email: Joi.string().email().required(), age: Joi.number().min(18) }); const { error } = schema.validate(req.body);; (2) express-validator — middleware-based, integrates with Express route handlers; (3) Zod — TypeScript-first schema validation; (4) validator.js — string validators and sanitizers. Never trust user input: validate on the server even if you validate on the client. Common attacks prevented by validation: SQL injection (use parameterized queries too), NoSQL injection (validate types), XSS (sanitize HTML), command injection (validate shell inputs). Always return clear validation error messages to clients (400 Bad Request) without exposing internal details.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Node.js answers easy to follow.