Difficulty: Intermediate
What is Cross-Site Scripting (XSS), what are its types, and how do you prevent it in a modern web app?
Cross-Site Scripting (XSS) happens when an application includes untrusted data in a page in a way that the browser runs it as script. The injected code runs with the victim's session on your origin, so it can read the DOM, make authenticated requests and steal any token stored in JavaScript-accessible storage. The core fix is context-aware output encoding, backed by sanitization of any HTML you must render and a strict Content Security Policy.
| Type | Where the payload lives | Example |
|---|---|---|
| Stored (persistent) | Saved in your database and served to every viewer | A product review on an e-commerce site containing a <script> tag |
| Reflected | In the request (URL or form), echoed back once | /search?q=<script>... rendered as "Results for ..." |
| DOM-based | Never reaches the server; client JS writes it unsafely | el.innerHTML = location.hash.slice(1) |
Stored XSS is usually the most damaging because it hits every user who views the page, including admins.
The browser cannot tell your script from the attacker's because both come from your origin. An attacker can:
localStorage and send tokens to their server.{}, Angular and Vue do the same for interpolation.innerHTML, document.write, eval, setTimeout(string), dangerouslySetInnerHTML and v-html bypass the framework's escaping. Prefer textContent.javascript: URLs in href in every version; only allow http: and https: schemes for user-provided links.script-src 'nonce-r4nd0m' 'strict-dynamic'; object-src 'none'; base-uri 'none' stops injected inline scripts from executing even if an encoding bug slips through.HttpOnly cookies for session tokens so a successful XSS cannot exfiltrate them.require-trusted-types-for 'script') in Chromium browsers to force all DOM sink writes through vetted policies.<script>. Payloads like <img src=x onerror=...> or <svg onload=...> get through.unsafe-inline in script-src largely defeats it.import DOMPurify from 'dompurify';
// Safe: React escapes the string, tags show as text
function Review({ text }: { text: string }) {
return <p>{text}</p>;
}
// Unsafe: raw HTML from users
function BadReview({ html }: { html: string }) {
return <div dangerouslySetInnerHTML={{ __html: html }} />;
}
// Acceptable: rich text sanitized with an allowlist
function RichReview({ html }: { html: string }) {
const clean = DOMPurify.sanitize(html, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'ul', 'li'],
ALLOWED_ATTR: ['href'],
});
return <div dangerouslySetInnerHTML={{ __html: clean }} />;
}
// Validate user links: only http(s)
const safeHref = (url: string) =>
/^https?:\/\//i.test(url) ? url : '#';
Default JSX interpolation is safe. Only reach for `dangerouslySetInnerHTML` with sanitized output, and validate URL schemes yourself.
Content-Security-Policy: default-src 'self';
script-src 'nonce-9f2c1a7b' 'strict-dynamic';
object-src 'none';
base-uri 'none';
frame-ancestors 'none'
Only scripts carrying the per-response nonce run, so an injected `<script>` without it is blocked. Generate a fresh nonce for every response.
Stored XSS, Reflected XSS, DOM-based XSS, Output Encoding, Content Security Policy, DOMPurify