Skip to the page

XSS and injection in the browser · core

XSS: stored, reflected and DOM-based; sources and sinks

Cross-site scripting is when attacker-controlled data runs as code in your page's origin, either stored on the server, reflected from the request, or created by your own JavaScript writing untrusted data into a dangerous DOM sink.

The notes

What you must know

  • Stored XSS: the payload is saved (a comment, a product review, a profile name) and runs for every viewer. Reflected XSS: the payload is in the request (a search query) and echoed back in the response. DOM XSS: client JS reads a source (location.hash, query, postMessage, API data) and writes it to a sink.
  • Dangerous sinks: innerHTML, outerHTML, insertAdjacentHTML, document.write, eval, new Function, setTimeout with a string, element.src/href with javascript: URLs, jQuery.html().
  • Impact: the script runs as your origin: it can read the DOM and non-HttpOnly cookies, read localStorage tokens, call your APIs as the user, change the page, and log keystrokes.
  • Main defence: output encoding by context (HTML body, attribute, URL, JS are different contexts) or using safe sinks like textContent. Input validation helps but is not enough.
  • When users must write HTML (rich text), sanitise with a maintained sanitizer (DOMPurify; Element.setHTML() is in Firefox 148 and Chrome 146 but not Safari yet).
  • Defence in depth: strict CSP, Trusted Types, HttpOnly cookies, short-lived tokens.

The red pen

Common traps: mistake → fix

  • Mistake: "We validate input, so we're safe from XSS"

    Fix: safety depends on encoding for the output context; the same text is safe in HTML text but dangerous in an href.

  • Mistake: "HTML-escaping makes any value safe"

    Fix: escaping does not stop javascript: URLs or values placed inside script or style.

  • Mistake: "XSS only steals cookies"

    Fix: with HttpOnly cookies the attacker still acts as the user from inside the page.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is XSS? Name the three types with an example each.
  2. What is a source and a sink in DOM XSS?
  3. Why is output encoding context-specific? Give two contexts that need different encoding.
  4. How would you allow users to post rich-text comments safely?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview