Security Playbook
06 · Web vulnerabilitiesOWASP A05:20258 min read

Cross-site scripting (XSS): running code in other people's browsers

If your page renders user content as HTML, an attacker can make it run their JavaScript for every visitor, with that visitor's session. The types of XSS, why React mostly saves you, and where it doesn't.

In one sentence

XSS is injection into HTML instead of SQL. Escape output by default, never inject raw HTML, and add a Content Security Policy as the safety net.

The idea

A product review that contains <script> is harmless text, unless the page puts it into the DOM as HTML. Then the browser runs it as if you wrote it, with access to the page, the user's session and every API the page can call.

XSS sandbox (nothing here ever runs)
Rendering
Try
Product page · comments
  • Great headphones, battery lasts all week!
What the browser does

✓

Escape output by default (React does it for you unless you use dangerouslySetInnerHTML). CSP is the second layer for when someone slips.
Nothing here is ever executed. The sandbox detects what the browser would run and shows it to you.

Three flavours

TypeWhere the payload livesExample
StoredSaved in your database and shown to othersA comment, a username, a product review
ReflectedIn the URL, echoed back in the response/search?q=<script>…</script> sent in a phishing email
DOM-basedNever reaches the server; client JS puts it in the pageelement.innerHTML = location.hash

What attackers do with it: steal session tokens readable from JavaScript, perform actions as the user (change email, transfer money), show a fake login form on your real domain, or log keystrokes.

How to prevent it

  • Escape by default. React, Vue, Svelte and templating engines escape {value} for you. Keep it that way.
  • Avoid raw HTML sinks: dangerouslySetInnerHTML, innerHTML, v-html, document.write. If you must render user HTML (rich text), sanitize it with a maintained library like DOMPurify.
  • Validate URLs: <a href={userUrl}> with javascript: is XSS even in React. Allow only https: and mailto:.
  • Content Security Policy: forbid inline scripts and unknown origins so injected code can't run even if it lands in the page.
  • HttpOnly cookies: a successful XSS still can't read the session cookie.
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'

Key takeaways

  • 01XSS lets attackers run JavaScript in your users' browsers, as them.
  • 02Escape output by default; framework escaping only fails when you bypass it.
  • 03Sanitize rich HTML and validate URL schemes.
  • 04CSP and HttpOnly cookies limit the damage when something slips through.

Check your understanding

1 of 3

What does XSS let an attacker do?

Related concepts