DOM-based XSS: when the browser runs the flaw

DOM-based XSS is cross-site scripting in which the vulnerable code runs in the browser: a script reads a value an attacker can influence, a source, and hands it to a function that interprets it as markup or code, a sink. The server may never see the dangerous part. Part of a URL, the fragment after #, is not sent to it at all, so a filter in front of the server cannot inspect what it never receives.

Section Web attacks Updated Weakness CWE-79

Quick facts

What runs
Client-side JavaScript on your own page, not server code
Weakness
CWE-79, improper neutralization of input during web page generation
OWASP category
A05:2025 Injection
Typical sources
location.hash, location.search, document.referrer, window.name, postMessage data
Typical sinks
innerHTML, document.write, eval, string arguments to setTimeout
Fragment
Not sent to the server (RFC 3986, section 3.5)
Main fix
Write untrusted data with textContent; enforce Trusted Types and a Content Security Policy as a second layer

Definitions and sink lists follow the OWASP DOM based XSS Prevention Cheat Sheet and the OWASP description of the attack. The Trusted Types material is from MDN.

Sources, sinks and the flow between them

Every DOM-based XSS bug has the same shape: a value travels from a place an outsider can control to a place that treats text as something executable. Security reviewers call the first end a source and the second a sink.

Sources: where the untrusted value comes from

A source is any browser-exposed value that someone other than your own code can set. The URL is the best known: location.hash for the fragment, location.search for the query string, and location.pathname. Others are document.referrer, window.name, data received through postMessage, web storage, and responses from APIs that echo user content. OWASP's cheat sheet adds that untrusted data can also arrive from a database or a back-end system and then be handled unsafely on the client.

Sinks: where the value becomes dangerous

A sink is a function or property that parses its input. MDN groups them into three kinds: HTML sinks such as innerHTML, document.write() and insertAdjacentHTML; JavaScript sinks such as eval(), the Function() constructor and string arguments to setTimeout(); and script-URL sinks such as the src of a script element or the URL given to a Worker.

The bug is the pair. Reading location.hash to pick a tab is harmless. Writing it into innerHTML is the flaw, because the text now goes through the HTML parser. Nothing in the data looks malicious in advance; the harm comes from where the page puts it.

Why the server never sees the fragment

A URL can end with # and a string. That string is the fragment. RFC 3986, section 3.5 says the fragment identifier is separated from the rest of the URI prior to dereferencing, and that the information inside it is dereferenced solely by the user agent. MDN's reference for the fragment says it in practical terms: it is not sent to the server when the URI is requested, and the client processes it after the resource is retrieved.

So a request for /page#section reaches the origin as a request for /page. Web server logs, reverse proxies, CDN edges and WAFs work from the request they receive, and the fragment is not in it. A script on the loaded page can still read it through location.hash.

The rest of the URL is different. The path and query string do travel with the request, and the browser exposes the query string to scripts as well. A DOM-based bug fed from location.search therefore leaves a trace on the server, while one fed from the fragment, from window.name or from a cross-window message does not.

How it differs from reflected and stored XSS

OWASP describes the split by where the unsafe handling happens. In server-side XSS the server puts untrusted data into the response without making it safe for its context. In DOM-based XSS the response can be entirely static, and the unsafe step is client-side processing. The injected script runs in the browser either way, which is why the page on cross-site scripting covers all three families and this page covers the one where the server's HTML is not the culprit.

That has two practical consequences. Output encoding in server templates does not fix it, because the server is not writing the dangerous value. And testing by requesting a page and reading the HTML will not find it; the flaw only shows once the page's scripts have run.

Single-page applications raise the odds. They read the URL, store and API data constantly and render it with client code, so a single careless innerHTML in a shared component can reach many routes.

Where a WAF helps and where it does not

A WAF filters requests. That is useful for some DOM-based bugs and blind to others, and the split follows the list of sources above.

What a request filter can see: the path, the query string, headers, cookies and the body. If the vulnerable page reads location.search, the suspicious value arrives in a request, and a rule that matches script-like content in parameters can record or refuse it. That gives some coverage, and it is a mitigation, not a fix. Encodings and variations are many, and a rule set that matches known shapes will not match all of them.

What it cannot see: the fragment, which is never sent. Also window.name, values passed between windows with postMessage, and anything the page assembles from local storage after it loads. For those flows there is no request to inspect, so no setting of the filter changes the outcome. The only fix is in the page's code.

Bridge WAF has three modes, off, monitor and block. Start in monitor: matches on query-string parameters are written to the activity log while every request is still served, so you can see which parameters carry script-like content and whether any legitimate traffic matches. Block comes after that review; the monitor mode page covers the order. A quiet log does not show that the page is safe, since the fragment-driven cases never appear in it.

Response headers are the other lever. A Content Security Policy is set on the response and enforced by the browser, which is where DOM-based execution actually happens. The security headers tool checks whether your site sends one.

How to prevent DOM-based XSS

  1. Write text as text. OWASP calls textContent the most fundamental safe way to put untrusted data into the DOM. It never parses its input as HTML.
  2. Change the sink, not the encoding. When a page uses innerHTML for plain text, switch to textContent instead of escaping for a dangerous call.
  3. Build elements with DOM methods. createElement, appendChild and setAttribute are safe for building an interface, with the OWASP caveat that setAttribute is safe only for attributes that do not run code. Never set event-handler attributes from data.
  4. Do not pass data to code-evaluating functions. Avoid eval, the Function constructor and string arguments to timers. Parse data with JSON.parse.
  5. Sanitize when you must render markup. If users legitimately supply HTML, run it through a maintained HTML sanitizer before it reaches the sink. OWASP names DOMPurify as one example.
  6. Check URLs you assign. A value placed in href or src should be validated against an allowed scheme and host. The same habit prevents open redirects.
  7. Check the origin of cross-window messages. A message handler should verify who sent the data before using it.

Trusted Types and CSP

The rules above rely on every developer remembering them on every line. Trusted Types moves the check into the browser. MDN describes the API as a way to make sure that data passed to a risky sink has first gone through a transformation function the developer defines, usually a sanitizer.

It is switched on from a Content Security Policy. The require-trusted-types-for 'script' directive makes the browser refuse plain strings at HTML, JavaScript and script-URL sinks: assigning a string to innerHTML throws a TypeError. The separate trusted-types directive lists the policy names your code may create. Code that has to write markup calls trustedTypes.createPolicy() once, in a place that can be reviewed, and every other assignment fails.

Two cautions from the same MDN page. A policy named default catches every string passed to a sink while enforcement is active. It exists to help migrate old code and is not recommended as a permanent setup. And the API supplies no sanitizer of its own; the policy is only as good as the function you write inside it. MDN marks the API as newly available across browsers since February 2026 and notes it may not work in older ones, so check the compatibility table for the browsers you support.

A plain Content Security Policy that forbids inline script and eval also narrows what an injected string can do. Treat CSP and Trusted Types as a second layer behind correct code, and roll them out in report-only form first so you see what would break.

Finding it in your own code

Start with a search of the front-end source for the sinks listed above, then trace each one backwards: where does its argument come from? If the answer is a URL part, storage, a message or an API response, read the code that prepares it. OWASP's cheat sheet describes this kind of variant analysis, following a value from a source such as location.hash to a sink such as document.write.

Build output deserves the same look. Dependencies and templates ship with their own sinks, and a bundled library that calls innerHTML on a value you pass in is your problem as much as the library's. Static analysis tools and a Trusted Types report-only policy both help here: the second one reports every assignment of a plain string to a sink as it happens, which turns a code audit into a list.

Questions

What is DOM-based XSS?

DOM-based XSS is cross-site scripting in which the page's own JavaScript reads an attacker-influenced value, a source, and passes it to a function that interprets it as markup or code, a sink. The unsafe step happens in the browser, not in the server's response.

Can a WAF block DOM-based XSS?

Only in part. A WAF can inspect the query string, headers and body of a request, so a value that arrives there can be recorded or blocked. It cannot see the URL fragment, which the browser does not send, or data passed between windows, so the fix has to be in the page's code.

Why does the server not see the part of the URL after #?

The fragment is handled by the browser alone. RFC 3986 says it is separated from the URI before dereferencing and dereferenced solely by the user agent, so a request for a page with a fragment arrives at the server without it.

How do you prevent DOM-based XSS?

Write untrusted data with textContent instead of innerHTML, avoid eval and other code-evaluating functions, sanitize any markup you must render, and validate URLs before assigning them. Trusted Types and a Content Security Policy add enforcement in the browser.

What are Trusted Types?

Trusted Types is a browser API, switched on through a Content Security Policy, that makes risky sinks such as innerHTML accept only values created by a developer-defined policy. Plain strings are rejected with a TypeError.