When a comment becomes a script
Someone posts the comment <img src=x onerror="steal()">. If your page drops that text into the HTML, the browser runs it — on every visitor's screen. That's cross-site scripting (XSS), one of the most common web attacks.
Treat user text as text
const comment = '<img src=x onerror="alert(\'hacked\')">';
const bad = document.querySelector("#bad");
// bad.innerHTML = comment; ← would run the attacker's code
const good = document.querySelector("#good");
good.textContent = comment;- Use textContent, createElement and setting properties — not innerHTML with user data.
- If you must build HTML strings, escape & < > " ' first.
- Frameworks like React escape by default; avoid their escape hatches (dangerouslySetInnerHTML).
- A Content Security Policy header adds a safety net by blocking unexpected scripts (Sikau's practice pages use one).
- Validate on the server too: never trust anything that comes from the browser.