← Back to HTML & CSS, page 8

html-css-0147 · Hard senior

A page shows a user's comment. How do you insert it safely, and what goes wrong with innerHTML?

Treat user input as text: set it with textContent or build elements with createElement, and use innerHTML only for trusted or sanitized markup. Escape for the exact context, never place user input in scripts or handler attributes, and add a CSP as a second layer.

Full answer

If a page puts user input into HTML as markup, the user can add their own markup, including scripts or event handlers. This is cross-site scripting (XSS). The attacker's code runs with the page's rights, so it can read data, act as the user and change the page.

The fix is to treat input as text and not as markup.

  • Use textContent (or innerText) to set text. The browser puts the characters in as text, so <b> shows as the characters <b> and does nothing.
  • Create elements with document.createElement and set properties, instead of gluing strings.
  • Use innerHTML only for markup that you wrote, or that has been sanitized by a trusted library. Newer browsers also offer sanitizer APIs, but check the support table first.
  • Where a string must be built, escape the five characters & < > " ' for the context. Escaping depends on where the value goes: in element text, in a quoted attribute, in a URL or in a script. Never put user input into a script, an event handler attribute or a javascript: URL. Check URLs for an allowed scheme before using them in href.
  • In templates on the server, use the engine's automatic escaping, and do not turn it off.

Layers of defence:

  • A Content Security Policy (CSP) header can block inline scripts and unknown sources, which reduces the damage of a mistake. It does not replace escaping.
  • Cookies with HttpOnly cannot be read by page scripts.
  • Validate input on the server, but escape on output, because the right escaping depends on where the data is shown.

Calling showSafe() shows the characters of the comment, and nothing runs. Calling showUnsafe() creates a real image element whose onerror handler runs, and the counter goes up. The escape helper turns the five characters into entities, which is correct for element text and quoted attributes only.

This example runs the unsafe case on purpose in a test page. Never do this with real user data.

html
<div id="safe"></div>
<div id="unsafe"></div>
<script>
  window.pwned = 0;
  const comment = '<img src="data:," onerror="window.pwned++">';
  function showSafe() { safe.textContent = comment; }
  function showUnsafe() { unsafe.innerHTML = comment; }
  const esc = s => s.replace(/[&<>"']/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
  window.escaped = esc('<a href="x">&</a>');
</script>

The unsafe case is run on purpose in a test page to show the problem. Never do this with real user data. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • XSS happens when user input becomes markup.
  • textContent inserts text, not markup.
  • Use innerHTML only for trusted or sanitized markup.
  • Escape for the right context on output.
  • CSP and HttpOnly cookies reduce damage.

Common mistakes

  • Using innerHTML with user input.
  • Escaping once and using the result in a different context, such as a URL.
  • Relying only on a CSP or only on input validation.

Follow-ups

  • Why is escaping done on output and not on input?
  • Which characters must be escaped in element text?

Tips

  • Explain the risk in one sentence, then give the textContent fix.
  • Mention escaping depends on the context, and name CSP as a second layer.