Skip to Content
Mengty Learns
Security

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.

explanationintermediateTested with asvs 5.0.0 (V1, V3)Updated Nov 26, 2026

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

TL;DR

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.

All three XSS types end in the victim's browser executing untrusted script in your origin.

Solution

Layer primary encoding/sanitization with a strong browser CSP (ASVS V1 & V3):

  1. Context-aware output encoding: Encode for the exact sink—HTML body (&lt;), HTML attribute, JavaScript data (JSON serialization, never string interpolation inside <script>), and URLs (validate https: / http: scheme before rendering href/src).
  2. React's boundary: JSX {userInput} is safe for text nodes. Never pass unsanitized HTML to dangerouslySetInnerHTML (sanitize first with DOMPurify), and always validate URL schemes before rendering <a href={userUrl}>.
  3. Strict CSP (defense in depth): Generate a fresh cryptographic nonce per response and set script-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

Overview of XSS Attack vs Context Encoding + Nonce CSP. 3 steps.
Overview3 steps in this flow

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

When to use
  • 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.
When to avoid
  • 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

Pros
  • 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.
Cons
  • 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