Course contentsShow
← Web Development
Lesson 2895 of 2,98252. Frontend SecurityFree lesson

DOM-Based XSS

Client-side XSS attacks that manipulate the DOM directly without server involvement.

DOM-Based XSS

You'll learn how XSS attacks can happen entirely on the client side by manipulating the Document Object Model without ever touching the server.


What Makes DOM-Based XSS Different

Unlike Reflected and Stored XSS, DOM-Based XSS happens entirely in the browser. The malicious payload never reaches the server—instead, vulnerable JavaScript code directly reads untrusted data (like URL parameters) and writes it into the page's DOM in an unsafe way.

Think of it like leaving your house keys under the doormat. You never invited a burglar into your home (server), but they found an unsecured entry point you created outside (client-side code).


How It Works

A common scenario involves JavaScript reading from window.location or document.referrer and inserting that data directly into the page:

// Vulnerable code
const params = new URLSearchParams(window.location.search);
const username = params.get('name');
document.getElementById('welcome').innerHTML = 'Hello ' + username;

An attacker crafts a URL like:

https://example.com?name=<img src=x onerror=alert('XSS')>

The malicious script executes because the JavaScript code itself put untrusted data into innerHTML.


Why It's Dangerous

Since the server never sees the payload, server-side filters and logging won't help. The vulnerability lives in your JavaScript code, particularly when using:

  • innerHTML, outerHTML
  • document.write()
  • eval(), setTimeout() with string arguments
  • Direct manipulation of location.href or document.location

Prevention

Always sanitize and escape user-controlled data before inserting it into the DOM. Use textContent instead of innerHTML when possible, and validate URL parameters before using them.

Key Takeaway: DOM-Based XSS exploits client-side JavaScript that unsafely handles untrusted input—the server never processes the attack, making it harder to detect and requiring careful frontend security practices.