Preventing XSS when rendering user content in templates
Knowing XSS and contextual output encoding.
The risk is XSS; default to escaped interpolation (EJS <%= %>, Pug #{}) so HTML is encoded, and avoid raw output (<%- %>) for untrusted data.
WHAT THIS TESTS: Whether you can name cross-site scripting and know that contextual output encoding, not just input filtering, is the primary template-layer defense.
A GOOD ANSWER COVERS: The vulnerability is XSS (cross-site scripting): if user-submitted text is written into HTML without encoding, an attacker can submit markup like a script tag that then executes in another user's browser, stealing sessions or performing actions as them. The straightforward defense is to rely on the template engine's default escaping. In EJS, <%= value %> HTML-escapes its output, while <%- value %> emits raw HTML. In Pug, #{value} escapes and !{value} is unescaped. So you simply use the escaping form for any untrusted data, which converts dangerous characters such as <, >, &, and quotes into HTML entities so the browser displays them as text rather than parsing them as tags. The unescaped form should be reserved for HTML you fully trust or have sanitized with a library like DOMPurify. Encoding must also be context-aware: HTML body, attribute, URL, and JavaScript contexts require different encoding.
COMMON WRONG ANSWERS: Saying the answer is SQL injection (that is the database layer, not view rendering). Using the raw output operator for user content. Believing input validation alone removes the need to encode on output. Stripping tags with a naive regex blocklist, which is easily bypassed.
LIKELY FOLLOW-UPS: Why is output encoding context-dependent (attribute vs script vs URL)? When is sanitization needed in addition to escaping? How does a Content-Security-Policy add a second layer?
ONE CONCRETE EXAMPLE: A comment field receives <script>steal()</script>. Rendered with EJS <%= comment %>, it becomes <script>steal()</script> and shows as literal text. Rendered with <%- comment %>, the script executes for every viewer.
Read the original → cheatsheetseries.owasp.org
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.