XSS: Cross-Site Scripting

Difficulty: Intermediate

Question

What is Cross-Site Scripting (XSS), what are its types, and how do you prevent it in a modern web app?

Answer

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.

The three types

TypeWhere the payload livesExample
Stored (persistent)Saved in your database and served to every viewerA product review on an e-commerce site containing a <script> tag
ReflectedIn the request (URL or form), echoed back once/search?q=<script>... rendered as "Results for ..."
DOM-basedNever reaches the server; client JS writes it unsafelyel.innerHTML = location.hash.slice(1)

Stored XSS is usually the most damaging because it hits every user who views the page, including admins.

Why it is dangerous

The browser cannot tell your script from the attacker's because both come from your origin. An attacker can:

  • Read localStorage and send tokens to their server.
  • Perform actions as the user (change email, place orders, transfer wallet balance).
  • Rewrite the page to show a fake login form.
  • Log keystrokes on the page.

How to prevent it

  1. Encode on output, per context. HTML body, HTML attributes, JavaScript strings and URLs each need different escaping. Template engines and frameworks do this by default: React escapes values in {}, Angular and Vue do the same for interpolation.
  2. Avoid dangerous sinks. innerHTML, document.write, eval, setTimeout(string), dangerouslySetInnerHTML and v-html bypass the framework's escaping. Prefer textContent.
  3. Sanitize HTML you must render. For rich text (blog posts, comments with formatting), run it through an allowlist sanitizer such as DOMPurify before inserting it.
  4. Validate URLs. React does not block javascript: URLs in href in every version; only allow http: and https: schemes for user-provided links.
  5. Add a Content Security Policy. A nonce-based CSP like 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.
  6. Use HttpOnly cookies for session tokens so a successful XSS cannot exfiltrate them.
  7. Consider Trusted Types (require-trusted-types-for 'script') in Chromium browsers to force all DOM sink writes through vetted policies.

Common mistakes

  • Sanitizing input once on the way in and assuming output is safe everywhere. Data can end up in a different context later.
  • Writing a home-grown regex to strip <script>. Payloads like <img src=x onerror=...> or <svg onload=...> get through.
  • Treating CSP as the primary fix. It is defence in depth; unsafe-inline in script-src largely defeats it.
How stored XSS reaches a victim. The payload is saved once and executes for every user who views it.
  1. Attacker posts a review: Review text contains an HTML event handler payload.
  2. Server stores it raw: No sanitization before saving or rendering.
  3. Victim opens product page: Review is inserted with innerHTML.
  4. Script runs on your origin: It acts with the victim's session.

Code examples

Safe and unsafe rendering in React

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.

Nonce-based Content Security Policy header

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.

Key points

  • XSS types: stored, reflected and DOM-based; stored usually has the widest impact.
  • Primary defence is context-aware output encoding, which frameworks do by default.
  • innerHTML, dangerouslySetInnerHTML, v-html and eval are the usual escape hatches that cause XSS.
  • Use DOMPurify for rich HTML and a nonce-based CSP as defence in depth.
  • HttpOnly cookies limit token theft but do not stop actions performed during the XSS.

Common follow-up questions

  • Does React fully protect you from XSS? Where can it still happen?
  • How does a nonce-based CSP work, and why is 'unsafe-inline' a problem?
  • What is the difference between DOM-based XSS and reflected XSS?
  • What are Trusted Types?

Interview tips

  • Lead with output encoding as the main fix; saying only "sanitize input" is a red flag for interviewers.
  • Name real sinks like `innerHTML` and `dangerouslySetInnerHTML` to show hands-on experience.
  • Explain why one XSS defeats localStorage token storage; it links nicely to JWT questions.

Concepts covered

Stored XSS, Reflected XSS, DOM-based XSS, Output Encoding, Content Security Policy, DOMPurify

More Web Security (OWASP, JWT, XSS, CSRF) questions