highCWE-79A03:2021

DOM-Based XSS

Malicious scripts executed by reading attacker-controlled data from the URL or browser APIs and writing it to the DOM using dangerous sinks like innerHTML or document.write.

How It Works

DOM XSS happens entirely in the browser — no server involvement. The attack URL contains a payload in the hash fragment or query string. Your JavaScript reads it with `location.hash` or `URLSearchParams` and writes it to the DOM. The server never sees the malicious payload, making server-side sanitization useless.

Vulnerable Code
// BAD: URL parameter written directly to DOM
const message = new URLSearchParams(location.search).get('msg');
document.getElementById('notification').innerHTML = message;
// URL: /page?msg=<img src=x onerror=alert(document.cookie)>
Secure Code
// GOOD: use textContent for plain text, DOMPurify for HTML
const message = new URLSearchParams(location.search).get('msg') ?? '';
// For plain text:
document.getElementById('notification').textContent = message;
// For HTML content:
import DOMPurify from 'dompurify';
document.getElementById('notification').innerHTML = DOMPurify.sanitize(message);

Real-World Example

DOM XSS is the most common type of XSS in modern SPAs. Google paid $7,500 for a DOM XSS found in their search results. JavaScript frameworks like React escape text by default, but developers who use dangerouslySetInnerHTML or direct DOM manipulation bypass those protections.

How to Prevent It

  • Use textContent or innerText instead of innerHTML whenever you're inserting plain text
  • When HTML is needed, sanitize with DOMPurify before insertion
  • Avoid document.write() entirely — it's deprecated and dangerous
  • Enable a strict CSP to mitigate damage if XSS does occur
  • In React: never use dangerouslySetInnerHTML without DOMPurify

Affected Technologies

ReactNext.jsjavascript

Data Hogo detects this vulnerability automatically.

Scan Your Repo Free

Related Vulnerabilities