Input validation versus output encoding
Knowing these are complementary, not interchangeable.
Validation checks input fits expected rules on entry; encoding makes data safe for a specific output context on exit. You need both; encoding is the real anti-XSS control.
WHAT THIS TESTS: Whether you understand that validating input at entry and encoding data at the point of use address different threats, and that XSS and injection are fundamentally output-context problems.
A GOOD ANSWER COVERS: Input validation runs when data enters the system. It asserts that input conforms to expectations: correct type, length, format, numeric range, or membership in an allowlist, and rejects or normalizes anything that does not. Its goals are data integrity, business-rule enforcement, and shrinking attack surface. Output encoding (or escaping) runs when data leaves the system into another context, transforming characters so they are interpreted as data rather than code in that specific context. The critical insight is that the safe transformation depends on the destination: HTML body, HTML attribute, JavaScript, URL, SQL, and shell each need different encoding, and the same value may be safe in one and dangerous in another. Therefore encoding, not validation, is the definitive defense against injection-class flaws like XSS; validation is a valuable additional layer but cannot be context-aware enough to be the sole control. You apply both: validate on entry, encode on exit.
COMMON WRONG ANSWERS: Saying validation alone stops XSS; treating the two as interchangeable; encoding once at input time and reusing the value across multiple contexts; only escaping for one context and assuming it covers all.
LIKELY FOLLOW-UPS: Why is the same data safe in one context and unsafe in another? Why encode at output rather than at input? How does parameterization relate to output encoding for SQL?
ONE CONCRETE EXAMPLE: In a route that creates a user, validate that req.body.age is an integer in a sane range and reject otherwise (input validation). Separately, when a later route renders that user's name into an HTML page, HTML-encode it so a name containing markup cannot inject script (output encoding). Validation guards the data; encoding guards the rendering.
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.