What are Trusted Types and how do they stop DOM XSS?

AdvancedSecurity interview questionBy , updated 23 November 2026

Short answer

Trusted Types is a browser security feature, switched on through Content Security Policy, that makes dangerous DOM sinks such as innerHTML, eval and script.src reject plain strings. They accept only typed values (TrustedHTML, TrustedScript, TrustedScriptURL) created by policies you define. Every route from a string to executable markup then goes through a few small functions you can review, which removes DOM-based XSS by construction.

The problem: DOM XSS lives in sinks

DOM-based XSS happens entirely in the browser. A source the attacker controls (location.hash, a query parameter, postMessage data, an API field) flows into a sink that parses it as HTML or code:

const name = new URLSearchParams(location.search).get("name");
banner.innerHTML = `Welcome, ${name}`; // ?name=<img src=x onerror=alert(1)>

A Content Security Policy with nonces blocks injected <script> tags, but it does not see this. The page's own trusted script is the one writing the markup. The usual advice, "sanitise before every innerHTML", depends on every developer and every dependency remembering every time, and code review cannot prove a negative across a large codebase.

Trusted Types change the default. With enforcement on, the browser itself refuses the unsafe pattern.

The three types and their sinks

Type Required by Examples
TrustedHTML Sinks that parse HTML innerHTML, outerHTML, insertAdjacentHTML, document.write, DOMParser.parseFromString, iframe.srcdoc
TrustedScript Sinks that run code from a string eval, new Function, setTimeout and setInterval with a string, script.text
TrustedScriptURL Sinks that load script from a URL script.src, new Worker(url), importScripts

Passing a plain string to any of these throws a TypeError and sends a CSP violation report. Safe APIs are not affected: textContent, setAttribute("class", ...), createElement and framework text rendering keep working, which is why the innerHTML vs textContent choice matters so much here.

Turning it on

Two CSP directives control it:

Content-Security-Policy: require-trusted-types-for 'script'; trusted-types app-html dompurify
  • require-trusted-types-for 'script' enforces types at the sinks.
  • trusted-types lists the policy names the page may create. Anything else calling createPolicy with another name fails, which stops a compromised dependency from making its own escape hatch. 'allow-duplicates' permits the same name twice, and 'none' forbids policies altogether.

Policies: the only way through

A policy is a named object whose functions turn strings into trusted values. The browser does not check what they do; it only guarantees that sinks accept nothing else. So the policy is where you sanitise or validate:

import DOMPurify from "dompurify";

const htmlPolicy = trustedTypes.createPolicy("app-html", {
  createHTML: (dirty) => DOMPurify.sanitize(dirty),
});

const scriptUrlPolicy = trustedTypes.createPolicy("app-script-url", {
  createScriptURL: (url) => {
    const parsed = new URL(url, location.origin);
    if (parsed.origin !== location.origin) throw new TypeError(`Blocked script URL: ${url}`);
    return parsed.href;
  },
});

preview.innerHTML = htmlPolicy.createHTML(userBio); // allowed
preview.innerHTML = userBio; // TypeError when enforced

DOMPurify also integrates directly: DOMPurify.sanitize(dirty, { RETURN_TRUSTED_TYPE: true }) returns a TrustedHTML created by DOMPurify's own policy, named dompurify by default, which is why that name appears in the trusted-types directive above. Keep the number of policies small and the code in one reviewed module; a policy that returns its input unchanged undoes the protection. Writing the sanitiser that sits inside such a policy is the exercise in an allowlist HTML sanitiser that resists mutation XSS.

The default policy

A policy named default is special: the browser calls it whenever a plain string reaches a sink, and uses its return value instead of throwing. It is a migration tool for code you cannot change yet, such as a third-party widget. Log what it sees, sanitise or reject, and aim to delete it. A permissive default policy is equivalent to not enforcing at all.

Rolling it out

  1. Report only. Send Content-Security-Policy-Report-Only: require-trusted-types-for 'script'; report-to csp. Nothing breaks; each violation report names the sink and a short sample of the value, with trusted-types-sink as the blocked URL.
  2. Group the reports by sink and file. Most come from a few places: a markdown renderer, a tooltip that builds HTML, an analytics snippet, a legacy jQuery plugin.
  3. Fix at the source. Replace innerHTML with textContent or DOM building where no markup is needed. Route the rest through one or two policies.
  4. Use a default policy only for what you cannot fix, with logging.
  5. Enforce, keeping reporting on to catch regressions from new code and dependency updates.

Angular has built-in Trusted Types support and documents the policy names it needs. Many libraries now pass trusted values through or create named policies; check their docs before allowlisting names. The frontend security design guide puts this alongside CSP, and rolling out a strict CSP is the same report-first approach for the rest of the policy.

Browser support in 2026

Chromium browsers have supported Trusted Types since version 83 in 2020. Safari added it in Safari 26, and Firefox enabled it by default in Firefox 148 in February 2026, so it is now Baseline newly available across the major engines. Older browsers ignore the directive, so the policy functions still run (sanitising still happens) but plain strings are not blocked. If code must run where trustedTypes is undefined, a small fallback that returns the policy's functions unchanged keeps the call sites working.

Follow-up questions interviewers ask

Does Trusted Types replace sanitising?

No. It enforces that sanitising, or some deliberate check, happens before every sink. The quality of the protection is the quality of your policy functions, so they still need a proven sanitiser such as DOMPurify.

How is it different from a nonce-based CSP?

A nonce CSP decides which scripts may load and run. Trusted Types control what already-running scripts may write into code-executing sinks. Use both: one stops reflected and stored script injection, the other stops DOM XSS.

Does React need Trusted Types?

React escapes text by default, so most React code never touches a sink. The risk is in dangerouslySetInnerHTML, refs that set innerHTML, and third-party code. Enforcing Trusted Types turns any of those into a visible error, which is the point, as discussed in where React does not protect against XSS.

Why does eval still fail after I create a TrustedScript?

Trusted Types and the CSP eval rules are separate checks. A strict script-src without 'unsafe-eval' still blocks string evaluation even when the value is typed. CSP has a newer 'trusted-types-eval' keyword that allows eval only for trusted values, but check support before relying on it. The better fix is to remove eval entirely.

Practise it in code

Interviewers rarely stop at the definition. These questions open in an editor with tests.

  1. Write an allowlist HTML sanitizer: unwrap unknown tags, block disguised javascript: URLs and resist mutation XSSHard50 min
  2. Roll out a strict Content Security Policy for an app with inline scripts and third-party analyticsHard45 min
  3. Escape HTML and sanitize URLs to close XSS holesMedium30 min
  4. Evaluate a Content-Security-Policy: 'self', nonces, hashes, wildcards, default-src fallback and 'strict-dynamic'Medium45 min