XSS & Content Security Policy (CSP)
Reflected, stored, and DOM XSS, context-aware output encoding, React's default escaping vs escape hatches, and CSP with nonces and strict-dynamic.
TL;DR
XSS happens when untrusted input is interpreted as executable script in a victim's browser (Reflected, Stored, or DOM-based). Prevent it primarily with context-aware output encoding (plus sanitizing rich HTML with DOMPurify and rejecting javascript: URLs), and add a nonce + 'strict-dynamic' Content Security Policy (CSP) as defense in depth.
Intent
Distinguish Reflected, Stored, and DOM XSS, know where React's automatic escaping stops, and pair context-aware encoding with a strict nonce-based CSP.
Problem
Many developers assume "React escapes everything" or "HTML-encoding < and > is enough". In reality, passing a user-supplied URL like javascript:alert(1) to <a href={url}>, using dangerouslySetInnerHTML without sanitization, or writing to element.innerHTML still gives attackers full script execution in the victim's origin.
Solution
Layer primary encoding/sanitization with a strong browser CSP (ASVS V1 & V3):
- Context-aware output encoding: Encode for the exact sink—HTML body (
<), HTML attribute, JavaScript data (JSON serialization, never string interpolation inside<script>), and URLs (validatehttps:/http:scheme before renderinghref/src). - React's boundary: JSX
{userInput}is safe for text nodes. Never pass unsanitized HTML todangerouslySetInnerHTML(sanitize first with DOMPurify), and always validate URL schemes before rendering<a href={userUrl}>. - Strict CSP (defense in depth): Generate a fresh cryptographic
nonceper response and setscript-src 'nonce-<random>' 'strict-dynamic'; object-src 'none'; base-uri 'none';. Avoid'unsafe-inline'and'unsafe-eval'.
Real-world analogy
▶ Flow: watch it work
XSS Attack vs Context Encoding + Nonce CSP
Press Start or tap any step dot to trace the path.
▸All steps (3)
Code
Watch out for React's two classic escape hatches (dangerouslySetInnerHTML and unvalidated href):
// UNSAFE: raw HTML injection and unvalidated URL scheme (allows javascript:alert(1))
function UnsafeProfile({ bioHtml, websiteUrl }: { bioHtml: string; websiteUrl: string }) {
return (
<div>
<div dangerouslySetInnerHTML={{ __html: bioHtml }} />
<a href={websiteUrl}>Website</a>
</div>
);
}
// SAFE: sanitize rich HTML and enforce https:/http: URL allowlist (ASVS V1, V3)
import DOMPurify from 'dompurify';
function safeHref(raw: string): string {
try {
const parsed = new URL(raw);
return parsed.protocol === 'https:' || parsed.protocol === 'http:' ? parsed.toString() : '#';
} catch {
return '#';
}
}
function SafeProfile({ bioHtml, websiteUrl }: { bioHtml: string; websiteUrl: string }) {
const cleanHtml = DOMPurify.sanitize(bioHtml);
return (
<div>
<div dangerouslySetInnerHTML={{ __html: cleanHtml }} />
<a href={safeHref(websiteUrl)} rel="noopener noreferrer">Website</a>
</div>
);
}When to use / when to avoid
- Use framework auto-escaping (React JSX text nodes) for plain text, and DOMPurify when you must render user-authored HTML.
- Validate URL protocols (https:/http:) before placing user input into href, src, or window.location.
- Deploy a nonce + strict-dynamic CSP on dynamic HTML responses to contain any missed encoding bug.
- Never rely on CSP alone while leaving raw innerHTML or dangerouslySetInnerHTML unescaped.
- Never add unsafe-inline or wildcard domains (https: *) to script-src—they defeat CSP.
How to implement
Audit dangerous sinks
Search the codebase for dangerouslySetInnerHTML, innerHTML, document.write, eval, and dynamic href/src props.
Enforce URL and HTML sanitization
Wrap rich HTML with DOMPurify and reject non-http(s): URLs.
Roll out CSP in Report-Only first
Start with Content-Security-Policy-Report-Only, inspect violation reports, then switch to enforcing mode.
Pros / Cons
- Context-aware encoding eliminates XSS at the root without breaking legitimate user text.
- Nonce + strict-dynamic CSP blocks injected inline scripts even if a template bug slips into production.
- Static sites without per-request HTML generation cannot easily rotate per-response nonces (they use script hashes instead).
- Third-party analytics or tag managers often conflict with strict CSP unless loaded via a nonced loader.
Relations
Check yourself
Check Yourself
1. A React component renders <a href={userWebsite}>Profile</a>. Is React's default JSX escaping enough to prevent XSS here?
2. What does 'strict-dynamic' do in a nonce-based Content Security Policy?
Sources
Related Notes
OAuth 2.1, OIDC & PKCE
What OAuth 2.1 changes (mandatory PKCE, no implicit grant, exact redirect matching), how OIDC adds identity via ID tokens, and the full Authorization Code + PKCE flow.
SQL Injection & Parameterized Queries
How SQL injection happens, why parameterized queries separate code from data, ORM raw-query escape hatches, and least-privilege database users.