Injection and output
Prevent cross-site scripting
Keep untrusted data as text, use framework escaping, and avoid browser sinks that interpret attacker-controlled strings as code or markup.
8 minute lesson
XSS happens when the browser interprets untrusted data as active page content. The safest default is to render text as text.
Use textContent or your framework’s normal escaped interpolation. Avoid innerHTML, inline event handlers, javascript: URLs, and bypass APIs. If the product must accept HTML, use a maintained sanitizer with a narrow allowlist.
message.textContent = userMessage
A profile name containing <img src=x onerror=alert(1)> is safe in escaped text. The same value becomes active when a preview feature assigns it to innerHTML.
Escaping once at input time is fragile because the value may later enter HTML, an attribute, or a URL. Keep the stored value unchanged and use a safe sink for its final context.
Trace one user-controlled value to every place it renders and record each sink. Test text, markup, attribute-breaking, and javascript: payloads, then prove none execute in the browser.
Lesson completed