Catalog My learning Blog
Browser Security Headers: CORS, CSP and Cookies Explained · Phase 3 · Lesson 17 · 7 min read

Trusted Types: Preventing DOM XSS

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: Enabling Trusted Types With a Migration Policy
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Explain why nonce-based CSP does not address DOM-based XSS, describe how Trusted Types converts every dangerous DOM sink into a type-enforced boundary, and outline a realistic migration path for an existing application.

Concept Explanation

A nonce-based CSP governs which scripts are allowed to execute. It has nothing to say about a page's own trusted script taking a value out of the URL and assigning it to element.innerHTML, or passing it to document.write, or to eval, or to a Function constructor. That is DOM-based XSS: the injection never passes through the server, the vulnerability lives entirely in client-side code, and every script involved is properly nonced. This is a large and growing share of real XSS, because applications moved rendering to the client.

Trusted Types attacks the problem at the type level. When a document enables it through the require-trusted-types-for 'script' CSP directive, the browser stops accepting plain strings at roughly sixty DOM sinks that can lead to code execution: innerHTML, outerHTML, document.write, the src of a script element, eval, setTimeout with a string, and so on. Those sinks accept only special objects, TrustedHTML, TrustedScript, and TrustedScriptURL, that can be produced exclusively by a policy the application registers with trustedTypes.createPolicy. Everything else throws a TypeError.

The value of this is structural rather than incremental. It converts an unbounded review problem, "audit every place any string reaches any dangerous sink anywhere in this codebase and all its dependencies," into a bounded one, "review the small number of policy functions we registered." The security of the entire application's DOM handling reduces to the correctness of code you can print on one page. Because the check is enforced by the browser, it also covers third-party libraries that the team never reviewed, which is precisely where DOM XSS most often hides.

The CSP directive has two parts worth knowing. require-trusted-types-for 'script' turns on the enforcement at the sinks. trusted-types names which policies may be created, optionally restricting them to a fixed list of names and allowing or forbidding duplicate names; trusted-types 'none' forbids creating any policy at all, which is the strongest setting for a page that genuinely needs no dynamic markup. A default policy, named default, is applied automatically to any string reaching a sink without an explicit conversion, which is the migration lever: it lets a large existing codebase adopt Trusted Types by routing everything through one sanitizer rather than rewriting every call site at once.

The migration path in practice is the same ratchet used for CSP generally. Turn on report-only with require-trusted-types-for and collect violations to build an inventory of sinks the application actually hits. Introduce a default policy that sanitizes with a vetted library such as DOMPurify, so behavior is preserved while violations become visible. Convert the highest-risk call sites to explicit named policies, shrinking what the default policy has to handle. Then enforce. The end state is a small number of audited policy functions and a browser-enforced guarantee that no other path to a dangerous sink exists.

SinkRequired typeTypical DOM XSS source
element.innerHTML, outerHTMLTrustedHTMLlocation.hash or a query parameter rendered into markup
document.write, writelnTrustedHTMLLegacy tag injection from a URL parameter
scriptElement.srcTrustedScriptURLA script URL built from user-controlled input
eval, Function, setTimeout with a stringTrustedScriptConfiguration or template data evaluated as code
element.setAttribute for event handlersTrustedScriptHandler markup assembled from untrusted data

Worked Example: Enabling Trusted Types With a Migration Policy

The code below shows the enforced directive, a named policy for the one place the application genuinely needs to build markup, and the default policy that keeps a large legacy codebase working while the conversion proceeds.

TypeScript
# Response header: nonce-based script control plus sink-level enforcement
Content-Security-Policy:
  script-src 'nonce-{PER_RESPONSE}' 'strict-dynamic';
  object-src 'none'; base-uri 'none';
  require-trusted-types-for 'script';
  trusted-types app-html default

// WITHOUT Trusted Types: classic DOM XSS, every script correctly nonced
const name = new URLSearchParams(location.search).get('name');
document.getElementById('greeting').innerHTML = 'Hello ' + name;
// ?name=<img src=x onerror=alert(1)>   -> executes

// WITH Trusted Types enforced, the same line now throws:
// TypeError: Failed to set the 'innerHTML' property on 'Element':
// This document requires 'TrustedHTML' assignment.

// A named, reviewed policy for the one place that needs markup
const appHtml = trustedTypes.createPolicy('app-html', {
  createHTML: (input) => DOMPurify.sanitize(input, { RETURN_TRUSTED_TYPE: false }),
});
el.innerHTML = appHtml.createHTML(userSuppliedMarkup);   // allowed

// A default policy as a migration bridge: applied automatically to any
// string that still reaches a sink directly, so legacy code keeps working
// while every conversion is centralized in one reviewable function.
trustedTypes.createPolicy('default', {
  createHTML: (input) => DOMPurify.sanitize(input),
  createScriptURL: (url) => {
    const u = new URL(url, location.origin);
    if (u.origin !== location.origin) throw new TypeError('blocked: ' + url);
    return u.href;
  },
});
Untrusted data flowing toward the DOM sinks, with Trusted Types inserting a single type-checked chokepoint that only a registered policy can pass, contrasted with the unbounded set of call sites that exist without it.
Untrusted data flowing toward the DOM sinks, with Trusted Types inserting a single type-checked chokepoint that only a registered policy can pass, contrasted with the unbounded set of call sites that exist without it.

Real-World Examples

  • Trusted Types shipped in Chrome 83 in May 2020 after being developed and deployed internally at Google, where the team reported that enforcing it across large applications eliminated DOM XSS as a class rather than reducing its frequency, because the browser refuses the dangerous assignment regardless of which first-party or third-party code attempts it.
  • Google has publicly described rolling Trusted Types out across its own major web applications and has published migration guidance built around the default-policy bridge, precisely because a codebase of that size cannot convert every DOM sink call site at once; the same staged approach, report-only first, then a sanitizing default policy, then named policies, is now the standard recommendation in the web.dev and MDN documentation.
Best PracticeTrusted Types turns "audit every string that reaches every DOM sink in our code and all our dependencies" into "audit the two policy functions we registered." That reduction is what makes it categorically different from a lint rule or a code review checklist, because the enforcement is performed by the browser and covers code you never wrote.

Review Questions & Answers

Because the vulnerable code is the page's own legitimate, properly nonced script. The attacker does not inject a script tag; they supply data through the URL, storage, or a message, and the application's trusted code passes that data to a sink such as innerHTML or eval. Every script involved is authorized by the policy, so there is nothing for the nonce check to reject. The dangerous operation is a data flow inside allowed code, not the execution of unauthorized code.

It replaces an unbounded audit, every string reaching every dangerous sink across the whole codebase and every dependency, with a bounded one, the handful of policy functions the application registered. It is categorical rather than incremental because the enforcement happens in the browser at the sink, so it applies to third-party library code the team never reviewed and to code paths nobody knew existed, which is exactly where DOM XSS tends to live.

The default policy is applied automatically to any string that still reaches a sink without an explicit conversion, which lets a large existing codebase adopt enforcement without rewriting every call site at once. The risk of keeping it permanently is that it must be permissive enough to handle every remaining path, so it becomes a single broad sanitizer applied to contexts with very different requirements. The goal is to shrink what it handles by converting high-risk call sites to explicit named policies.

Start with require-trusted-types-for in a report-only policy to inventory which sinks the application actually reaches and from where. Add a default policy that sanitizes with a vetted library so behavior is preserved and violations are observable. Convert the highest-risk call sites to explicit named policies, narrowing the default policy's scope. Then switch to enforcement, and optionally tighten the trusted-types directive to a fixed list of allowed policy names so no new policy can be introduced without a policy change.