Skip to content

Cross-Site Scripting, Explained: Reflected, Stored and DOM-Based XSS

Cross-site scripting lets attacker-controlled input run as JavaScript in a victim's browser. Here is what XSS is, how its three variants differ, and the layered defense that shuts all of them down.

SelfSec Team 7 min read

Part 1 of 6From the Cross-Site Scripting series

At a glance

CWE-79
Interpreter
Browser HTML parser and JavaScript engine
Required condition
Untrusted data reaches an HTML, attribute, JavaScript or URL context without encoding for that context.
Potential impact
Script runs as the victim inside the trusted origin: session abuse, data theft and account takeover.
Primary defense
Context-aware output encoding through auto-escaping templates, plus safe DOM sinks and a strict CSP.

Safe practice: use benign proof only, in a disposable local lab or on a system you are explicitly authorized to test.

Cross-site scripting (XSS) is what happens when an application lets untrusted input become part of the page's executable content. Instead of corrupting a database query like SQL injection, XSS corrupts the HTML and JavaScript the victim's browser runs. The browser trusts the page's origin, so it trusts the injected script with it — and runs that script with full access to the user's session.

In the OWASP Top 10:2025, XSS sits inside A05 Injection, a category OWASP notes includes more than 30,000 cross-site scripting CVEs. XSS is not a single bug but a family of three. They differ in where the untrusted data enters and who renders it into the page. This post is the map: it covers what unites them and links out to a deep-dive for each variant.

The mental model: one document, several parsers

A browser does not read a page as one kind of text. The HTML parser hands attribute values, script blocks and URLs to different parsers, and each one has its own characters that end data and start code. Encoding that is correct in one context can be useless in the next.

Where the value lands Example sink Input that breaks out Correct handling
HTML body <p>VALUE</p> <img src=x onerror=alert(1)> HTML-encode <, >, &, " and '
Quoted attribute <input value="VALUE"> " autofocus onfocus="alert(1) Attribute-encode and always quote the attribute
JavaScript string <script>let q = 'VALUE';</script> ';alert(1);// or </script> Keep data out of inline script; pass it as JSON in a data attribute
URL attribute <a href="VALUE"> javascript:alert(1) Allow only http and https URLs, then attribute-encode
Client-side template {{VALUE}} compiled at runtime {{constructor.constructor('alert(1)')()}} Never let user input into a template the framework compiles

The URL row is the one that surprises people: javascript:alert(1) contains no character that HTML encoding changes, so a perfectly encoded value is still executable. Every row comes down to the same question: does the parser that reads this value treat any of it as markup or code?

How it happens

Every XSS bug is the same mistake in different clothing: data that the application expects to be inert text is instead interpreted as markup or code. The data crosses a trust boundary — a URL parameter, a stored comment, a postMessage event — and lands in a sink that builds the page without encoding it first.

$name = $_GET['name'];
echo "<h1>Welcome, " . $name . "</h1>";

For ?name=Alice this is fine. But name is attacker-controlled and is being dropped straight into HTML, so it can carry a tag instead of a name.

The three variants

The differences come down to the path the payload travels before it executes.

Reflected XSS — the input is sent in a request and immediately echoed back in the same response. The payload lives in the URL and fires only for whoever follows the crafted link. The reflected XSS deep-dive walks through it end to end.

https://shop.example/search?q=<script>alert(document.domain)</script>

Stored XSS — the payload is persisted server-side (a comment, a profile bio, a support ticket) and served to every viewer of that content, with no link to click. See stored XSS, and blind XSS for the case where it fires in a back-office view the attacker never sees.

<p class="comment">Great post! <img src=x onerror=alert(document.domain)></p>

DOM-based XSS — the flaw is entirely client-side. JavaScript already on the page reads an attacker-controllable source and writes it into a dangerous sink. The payload can sit in the URL fragment, so the server never even receives it. The DOM-based XSS deep-dive covers sources and sinks.

document.getElementById('out').innerHTML = location.hash.slice(1);

Reflected, stored and DOM-based are the same vulnerability class viewed from three angles — the question is only where the untrusted data enters and who renders it. Each has its own deep-dive in this series.

What an attacker gains

Once arbitrary JavaScript runs on the page, it acts with the victim's full authority:

  • Steal session cookies that are not marked HttpOnly, hijacking the account.
  • Read the DOM — CSRF tokens, profile data, anything rendered on the page.
  • Forge requests as the victim, including state-changing actions like email or password changes.
  • Rewrite the page to phish credentials inside a genuinely trusted origin.

The end state is frequently account takeover. Stored XSS amplifies this further: one injection can hit thousands of sessions, including the admins who moderate the content.

The fix: encode for context, then defend in depth

There is no single switch, but the variants share one root defense: context-aware output encoding. Encode data for the exact place it lands so the browser always reads it as text, never as markup or code.

$name = $_GET['name'];
echo "<h1>Welcome, " . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . "</h1>";

Now the < becomes &lt; and the browser sees inert text. Layer the rest on top:

  • Use a templating engine that auto-escapes by default, and keep encoding correct for the HTML, attribute, JavaScript and URL contexts.
  • For DOM sinks, prefer safe APIs like textContent and setAttribute over innerHTML, and adopt Trusted Types where supported.
  • Set a strict Content-Security-Policy that blocks inline scripts, so a single missed sink is far harder to exploit.
  • Mark session cookies HttpOnly so script cannot read them, and Secure so they never travel over plain HTTP.

The same encoding rule in ASP.NET Core, when a handler writes HTML itself:

using System.Text.Encodings.Web;

app.MapGet("/welcome", (string? name) =>
{
    var safeName = HtmlEncoder.Default.Encode(name ?? "");
    return Results.Content($"<h1>Welcome, {safeName}</h1>", "text/html; charset=utf-8");
});

In practice, let the template engine do this: Razor's @name, Blazor, React, Angular and Vue all encode text by default. The risk concentrates in their escape hatches — Html.Raw, MarkupString, dangerouslySetInnerHTML, v-html — and in hand-written DOM code.

On the client, write text with textContent and pass user-authored HTML through a maintained sanitizer immediately before it is inserted:

import DOMPurify from 'dompurify';

function renderComment(container, comment) {
  const author = document.createElement('strong');
  author.textContent = comment.author;

  const body = document.createElement('div');
  body.innerHTML = DOMPurify.sanitize(comment.html);

  container.replaceChildren(author, body);
}

The DOM-based example above is fixed the same way: assigning location.hash.slice(1) to textContent instead of innerHTML turns the payload into visible text. Do not modify sanitized markup afterward and keep the sanitizer current; mutation XSS explains how a later parse can undo an earlier clean.

For the policy itself, a nonce-based CSP refuses any script the server did not mark with a fresh, unpredictable value generated for that response:

Content-Security-Policy: script-src 'nonce-{RANDOM}' 'strict-dynamic'; object-src 'none'; base-uri 'none'

Fixes that do not hold

  • Stripping <script> tags: event handlers, SVG, javascript: URLs and mixed-case tags execute without one.
  • Encoding on input instead of output: the same stored value may later land in HTML, an attribute, a script or a URL, and each needs different treatment.
  • HTML-encoding everything: it does nothing for a value placed in a JavaScript string or an href.
  • Relying on CSP alone: a policy with 'unsafe-inline' or a broad host allowlist is easy to bypass, and CSP never fixes the injection itself.
  • Relying on HttpOnly: it protects the cookie value, not the session — injected script can still send requests as the user.
  • Adding a WAF: filters see one encoding of the request, while the browser decodes and parses the final page; evasion variants are routine.

A developer review checklist

  1. Inventory every place request or stored data is rendered: server templates, client-side rendering, emails and admin views.
  2. Keep auto-escaping on and review each opt-out such as Html.Raw, MarkupString, |safe, dangerouslySetInnerHTML, v-html and innerHTML.
  3. Encode for the destination context, and validate URL schemes before writing href or src.
  4. Sanitize user-authored HTML with a maintained library as the last step before insertion.
  5. Never compile user input into client-side templates.
  6. Deploy a nonce-based CSP and mark session cookies HttpOnly, Secure and SameSite.
  7. Test with a harmless alert(1) marker and confirm execution in a real browser, not just a reflection in the response.

References

Module: Cross Site Scripting. How it probes: Context-aware breakout payloads for HTML, attribute, JavaScript-string, javascript: URL and client-side template contexts across query, form, path and WebSocket inputs, with mutation and filter-bypass variants where they apply. How it confirms: A reflection only counts when it is unencoded and a benign control does not match; on GET requests a headless browser then loads the page, and only an alert dialog that actually fires confirms the finding. A finding moves from Possible to Confirmed only after this check. Reported as CWE-79 · ATT&CK T1059, T1189 · SARIF 2.1.0.
How SelfSec proves this one
Module
Cross Site Scripting
How it probes
Context-aware breakout payloads for HTML, attribute, JavaScript-string, javascript: URL and client-side template contexts across query, form, path and WebSocket inputs, with mutation and filter-bypass variants where they apply.
How it confirms
A reflection only counts when it is unencoded and a benign control does not match; on GET requests a headless browser then loads the page, and only an alert dialog that actually fires confirms the finding.
Reported as CWE-79 · ATT&CK T1059, T1189 · SARIF 2.1.0

A reflected response alone is not enough to promote a Cross-Site Scripting finding. The classical engine has to confirm the behavior before it reaches the report. See the detection engine

SelfSec scanner

Find Cross-Site Scripting in your own app

Reading about the class is one thing. SelfSec tests for it against an application you are authorized to assess, and only calls it real when independent evidence agrees.

Join the launch list