DOM XSS happens when a string reaches an injection sink such as innerHTML, outerHTML, insertAdjacentHTML, document.write, eval, script.src or new Function. Trusted Types let you enforce, through CSP (require-trusted-types-for 'script'), that these sinks only accept typed objects (TrustedHTML, TrustedScript, TrustedScriptURL) created by named policies you control. Any plain string assignment throws. That turns DOM XSS from "find every bug by review" into "audit a handful of policies". It's the technique Google credits for largely eliminating DOM XSS in apps that adopted it.
Content-Security-Policy: require-trusted-types-for 'script'; trusted-types app-sanitizer
const sanitizer = trustedTypes.createPolicy('app-sanitizer', {
createHTML: (input) => DOMPurify.sanitize(input),
createScriptURL: (url) => {
const u = new URL(url, location.origin);
if (u.origin === location.origin || u.origin === 'https://cdn.example.com') return u.href;
throw new TypeError('Untrusted script URL: ' + url);
},
});
el.innerHTML = userBio; // throws TypeError under enforcement
el.innerHTML = sanitizer.createHTML(userBio); // allowed
el.textContent = userBio; // fine: not an HTML sink
trusted-types <names> restricts which policy names can be created, so a malicious script can't simply create its own permissive policy. Add 'none' to forbid all policies, or 'allow-duplicates' if a library recreates its policy.default policy is called automatically for any plain string reaching a sink. It's a migration tool: log or sanitise there while you fix call sites, then remove it.TrustedHTML directly (RETURN_TRUSTED_TYPE: true).Content-Security-Policy-Report-Only: require-trusted-types-for 'script' with a reporting endpoint. Violation reports name the sink and include a sample of the offending code.textContent, setAttribute for non-URL attributes, DOM construction, framework templating) over policies. React's JSX doesn't hit sinks except via dangerouslySetInnerHTML.createPolicy.Trusted Types have been in Chromium-based browsers since 2020. Other engines have been implementing them more recently, so check current support tables. Enforcement is still worth it with partial coverage: violations caught in Chromium (in CI, end-to-end tests and production reports) fix the bug for every browser. For non-supporting browsers, the small trustedTypes polyfill or a "tinyfill" (if (!window.trustedTypes) window.trustedTypes = { createPolicy: (n, p) => p }) keeps your code paths uniform.
createHTML: s => s) just relabels the bug. Policies must actually validate or sanitise.script.src, importScripts, Worker URLs), which need TrustedScriptURL.<script>, Trusted Types guards DOM sinks.trusted-types allow-list, the default policy as a migration aid.Spotted a mistake or a rights concern? Report an issue