Updated 22 October 2026. Trusted Types became a Baseline 2026 web platform feature in February 2026, making this a timely upgrade for teams hardening modern browser applications. Trusted Types helps stop DOM-based cross-site scripting (DOM XSS) by making selected dangerous browser APIs reject ordinary strings when enforcement is enabled. It complements—not replaces—context-aware output encoding, HTML sanitisation and a well-designed Content Security Policy (CSP).
1. Why innerHTML can turn data into code
DOM XSS happens when attacker-controlled input—from a URL fragment, form, API response or stored profile field—reaches a browser 'injection sink' that interprets it as HTML or script. Examples include innerHTML, outerHTML, insertAdjacentHTML and document.write. Assigning an untrusted string to one of these APIs can turn data into executable markup. Trusted Types lets the browser require a special TrustedHTML (or related) object instead of a raw string.
const target = document.querySelector('#message');
const input = new URLSearchParams(location.search).get('message') ?? '';
// Avoid: this parses untrusted input as HTML.
target.innerHTML = input;
// Prefer this when you only need text:
target.textContent = input;The simplest and safest fix is often to avoid HTML parsing entirely. Use textContent for ordinary text, framework-provided escaping for templates, and fixed DOM construction where practical. Reserve HTML sanitisation for features that genuinely need rich text, such as user-authored descriptions.
2. Discover risky sinks before enforcing anything
- Search application code and templates for innerHTML, outerHTML, insertAdjacentHTML, document.write, DOMParser.parseFromString and script URL creation; review any third-party widgets that use them.
- Trace whether each value can contain untrusted input. Refactor plain-text rendering to textContent or equivalent safe framework bindings.
- Identify the small number of rich-HTML paths that genuinely need sanitisation. Choose and maintain a reviewed sanitizer such as DOMPurify.
- List the user journeys most likely to break when a policy becomes enforced: rich-text editing, Markdown previews, analytics widgets, embedded checkout and legacy libraries.
3. Start with a report-only Trusted Types policy
Deploy the following example as HTTP response headers on a staging page. The example endpoint is a placeholder: provision a secure report receiver before using it. Report-only mode records prospective violations without blocking them. Keep your existing enforced CSP in place; this is a separate trial policy.
Reporting-Endpoints: csp="https://example.com/csp-reports"
Content-Security-Policy-Report-Only: require-trusted-types-for 'script'; trusted-types app-html; report-to csp; report-uri /csp-reportIn a test browser, inspect the Console for Trusted Types violations and watch SecurityPolicyViolationEvent entries. Exercise real user journeys, not just the homepage. Report-only findings reveal migration work; they do not mean the browser has blocked the unsafe operation.
document.addEventListener('securitypolicyviolation', (event) => {
console.info('CSP test:', event.effectiveDirective, event.disposition);
});4. Create a narrowly scoped sanitising policy
When you must render untrusted rich HTML, pass it through a maintained HTML sanitizer. The following example uses DOMPurify (install it as an application dependency). The policy name app-html must match the trusted-types directive. Returning a string from the createHTML callback is intentional: the browser wraps the sanitized result in TrustedHTML. Do not create a policy that simply returns the original input.
import DOMPurify from 'dompurify';
const policy = window.trustedTypes?.createPolicy('app-html', {
createHTML: (dirty) => DOMPurify.sanitize(dirty, {
RETURN_TRUSTED_TYPE: false
})
});
function renderRichText(target, userHtml) {
const clean = policy
? policy.createHTML(userHtml)
: DOMPurify.sanitize(userHtml);
target.innerHTML = clean;
}This fallback still sanitises content in browsers without Trusted Types. Keep DOMPurify updated and avoid modifying the sanitized markup afterward. Do not use the same policy to approve arbitrary script text or script URLs. If your framework already provides safe HTML rendering, follow its documented Trusted Types integration rather than layering conflicting transformations.
5. Enforce only after violations are resolved
Once staging is clean and policy creation is controlled, move the directives into the enforced Content-Security-Policy response header. Add them to your existing CSP rather than replacing important script, frame, object and base restrictions. The following is a directive fragment, not a complete production policy:
Content-Security-Policy: require-trusted-types-for 'script'; trusted-types app-htmlWith enforcement active in a supporting browser, assigning a plain string to a protected HTML sink generally throws a TypeError unless a default policy is in use. A policy named default can help migrate legacy code, but because it automatically transforms string assignments, it can conceal call sites that still need refactoring. Prefer explicit, audited policies and avoid broad policy-name wildcards.
// Staging-only negative test, on a page with enforcement active:
const probe = document.createElement('div');
try {
probe.innerHTML = '<b>test</b>';
console.warn('No Trusted Types rejection: check enforcement/browser');
} catch (error) {
console.info(error.name); // TypeError is expected
}6. Production rollout checklist
- Ship the report-only policy to staging, then a limited production audience, and review real violations before enforcement.
- Use textContent for plain text and audited sanitisation for rich HTML; patch any third-party libraries that use unsafe sinks.
- Restrict Trusted Types policy names to the minimum necessary; do not create a policy that returns unsanitized input.
- Test on your supported browser matrix, including older browsers that may ignore the directives.
- Enforce gradually, watch client-side exceptions and failed user journeys, and keep a rollback plan for the CSP header.
- Keep the existing XSS protections: context-aware output encoding, a strict script CSP where feasible, secure dependency updates and security reviews.
7. What a Zenith audit can and cannot confirm
Zenith's security.no-csp audit finding is relevant when a site does not send a Content-Security-Policy header. This tutorial goes further into browser-side Trusted Types adoption. A missing-CSP finding is not a Trusted Types-specific finding, and clearing that finding does not establish that the app sanitises every dangerous DOM sink. Confirm actual enforcement in browser DevTools and with application tests.
Official documentation and further reading
- MDN Trusted Types API (Baseline 2026): https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API
- MDN require-trusted-types-for directive: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy/require-trusted-types-for
- MDN trusted-types directive: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy/trusted-types
- MDN CSP report-only deployment: https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP
- OWASP XSS Prevention Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet
- Google web.dev Trusted Types migration guide: https://web.dev/articles/trusted-types
Glossary
- DOM XSS
- Cross-site scripting caused by untrusted data reaching a browser API that interprets it as HTML or executable code.
- Injection sink
- An API such as innerHTML that can interpret a string as HTML, JavaScript or another active format.
- TrustedHTML
- A browser-created typed object intended for injection sinks that expect HTML, issued by a Trusted Types policy.
- Trusted Types policy
- A named transformation that creates trusted objects; its callback must validate or sanitise untrusted content appropriately.
- Report-only CSP
- A Content Security Policy delivered without enforcement so potential violations can be observed before a blocking rollout.