Sikau

Web essentials · Day 13 · about 30 min

Security: injection and XSS

Never let text become code.

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.

The rest of this lesson

  • How XSS attacks really workexplain
  • Layers of defenceexplain
  • Safe or not?predict
  • Escape orderpredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 16 lessons of Web essentials