Cross-Site Scripting (XSS) Prevention

How attackers inject scripts through untrusted data, and how escaping, safe APIs and sanitisation stop them.

Intermediate · about 3 hours · difficulty 3/5

Learn first: Browser Security Model, DOM Manipulation

XSS happens when untrusted data ends up executing as code in your page. Once an attacker's script runs on your origin, it can do anything the user can: read data, make requests as them, steal tokens stored in JavaScript-accessible places and deface the page. It remains one of the most common web vulnerabilities.

Types

  • Stored XSS: malicious input is saved (a comment, a profile name) and served to other users.
  • Reflected XSS: input from the URL is echoed straight into the page.
  • DOM-based XSS: client-side code moves data from a source (location.hash, postMessage, API data) into a dangerous sink.

Dangerous sinks

innerHTML, outerHTML, document.write, insertAdjacentHTML, eval, new Function, setTimeout("string"), javascript: URLs in href and inline event handler attributes.

Defences

  • Use safe APIs: textContent instead of innerHTML. Frameworks escape text by default: React's JSX, Vue's {{ }} and Angular templates are safe for text.
  • Framework escape hatches remove that protection: React's dangerouslySetInnerHTML, Vue's v-html, Svelte's {@html}. If you must render user HTML (Markdown, rich text), sanitise it with DOMPurify first.
  • Validate URLs before using them in href or src: allow only https: (and maybe mailto:).
  • Be careful with third-party scripts and dependencies; they run with full privileges.
  • Add a Content Security Policy as defence in depth, and consider Trusted Types to lock down DOM sinks.

Good enough to move on

You can spot the XSS in a code snippet that uses innerHTML or an unchecked user-supplied link, fix it with safe APIs or DOMPurify, and explain why React escaping does not cover href="javascript:...".

Key concepts

  • Stored, reflected and DOM-based XSS
  • Dangerous DOM sinks
  • Framework auto-escaping
  • dangerouslySetInnerHTML and v-html
  • Sanitising HTML with DOMPurify
  • Validating URLs and javascript: links
  • Trusted Types

Mini project

Build a deliberately vulnerable comments page (innerHTML, unchecked profile links), exploit it locally with a harmless alert payload, then fix every hole and write a short explanation of each fix.

Check yourself

React escapes text in JSX. Give an example of React code that is still vulnerable to XSS.

Free resources