Join our Newsletter — 33% off our NHI Course
Home› Guides› Trusted Types and DOM XSS Prevention Guide: Lock…
Guide Web & API Security

Trusted Types and DOM XSS Prevention Guide: Lock Down DOM Sinks with Browser Enforcement

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 27 October 2026 14 min read
On this page

DOM-based cross-site scripting survives code review because the dangerous call, a string assigned to innerHTML or passed to eval(), can sit anywhere in hundreds of thousands of lines of front-end code and third-party libraries. Trusted Types moves the defence into the browser: once enforced through Content Security Policy, the browser refuses plain strings at more than 60 injection sinks and accepts only typed values created by policies you name and review. This guide explains how the API and its two CSP directives work, how to design policies, how to migrate a large application using report-only mode, and how to measure progress. It is written for front-end engineers, application security teams and reviewers who already know the basics of XSS and CSP and want to make DOM XSS structurally hard rather than chase it bug by bug.

Key takeaways

  • Trusted Types turns sinks into type checks. With require-trusted-types-for 'script' set, assigning a string to a sink such as Element.innerHTML throws a TypeError; only TrustedHTML, TrustedScript or TrustedScriptURL objects are accepted.
  • Your security surface shrinks to the policies. Every value reaching a sink must pass through a named policy, so review effort concentrates on a few small functions instead of every call site.
  • The trusted-types directive is the allow-list. It names which policies may be created; omit wildcards and 'allow-duplicates' unless you have a documented reason.
  • Roll out in report-only mode first. Send Content-Security-Policy-Report-Only with the Trusted Types directives, collect violation reports, refactor, then enforce.
  • A policy is only as safe as its transformation. Trusted Types guarantees a policy ran; it does not guarantee the policy sanitised correctly. A permissive default policy can quietly undo the whole control.

What Trusted Types is and where it sits

DOM XSS happens when attacker-controlled data reaches a browser API that interprets it as HTML or code. The Trusted Types API, specified by the W3C Web Application Security Working Group (the specification is an Editor's Draft, last dated 7 October 2026 when checked on 27 October 2026, and may change), gives developers a way to lock those APIs, called injection sinks, so they only accept non-spoofable typed values. MDN groups the sinks into three kinds, each matched by a type:

Sink kindTrusted type requiredExample sinks (MDN list)Typical policy behaviour
HTML sinksTrustedHTMLElement.innerHTML, outerHTML, insertAdjacentHTML, document.write(), DOMParser.parseFromString(), iframe.srcdoc, Range.createContextualFragment(), setHTMLUnsafe()Sanitise with a maintained HTML sanitiser, or escape
JavaScript sinksTrustedScripteval(), Function() and async or generator function constructors, setTimeout() and setInterval() with a string, HTMLScriptElement.text, textContent and innerText on a script elementUsually refuse: return nothing, so the call fails
Script URL sinksTrustedScriptURLHTMLScriptElement.src, Worker() and SharedWorker() URLs, importScripts(), ServiceWorkerContainer.register()Allow only an explicit list of origins or paths

The API has two halves. The JavaScript half is the trustedTypes global (a TrustedTypePolicyFactory, available in windows and workers) that creates policies. The enforcement half is two CSP directives. Without the directives, the API is only a convention: code can still pass strings to sinks. With them, the browser does the checking at runtime.

  • Relationship to CSP: a strict, nonce-based CSP stops injected script elements from running; Trusted Types stops your own code from feeding untrusted strings into sinks. They address different halves of XSS and work best together. See the Content Security Policy Guide.
  • Relationship to output encoding: encoding and safe sinks such as textContent remain the first fix. OWASP's DOM based XSS Prevention Cheat Sheet states that using the right output method is the best way to fix DOM XSS. Trusted Types makes the unsafe sinks hard to reach by accident. See the Cross-Site Scripting (XSS) Prevention Guide.
  • Secure context only: web.dev notes that Trusted Types works only in secure contexts such as HTTPS and localhost.

The two CSP directives in detail

Directive or keywordWhat it doesGuidance
require-trusted-types-for 'script'Turns on enforcement. String values passed to DOM XSS sinks are rejected with a TypeError unless a default policy converts them.The only accepted value is 'script'. Start in report-only.
trusted-types <policyName> ...Allow-list of policy names that trustedTypes.createPolicy() may create. An unlisted name throws and dispatches a SecurityPolicyViolationEvent.List every policy by name, including framework policies.
trusted-types 'none' (or the directive with no names)Disallows creating any policy.Useful for pages that should never write HTML from strings.
* as a policy nameAllows any unique policy name.Avoid in production: it removes the review gate.
'allow-duplicates'Allows a policy name to be created more than once.Avoid: a second policy with a trusted name can be created by other code. Use only when a library genuinely needs it.
'trusted-types-eval' (keyword in script-src)Re-enables eval() and similar functions only when Trusted Types are enforced and typed values are passed.MDN advises avoiding it unless absolutely necessary, and using it instead of 'unsafe-eval' when eval is unavoidable, so browsers without Trusted Types still block eval.

Policy names may contain only alphanumeric characters and the characters -#=_/@.%, according to MDN. A minimal production header for an application with one sanitising policy and one script loader policy looks like this:

Content-Security-Policy: require-trusted-types-for 'script'; trusted-types app-sanitize app-script-loader; report-to csp-endpoint

MDN notes that report-to replaces the deprecated report-uri, and that until report-to is broadly supported both can be specified. ASVS 5.0 V3.4.7 requires the CSP header to specify a location to report violations, which you will need for Trusted Types triage in any case.

Designing policies that are worth trusting

A policy is created with trustedTypes.createPolicy(name, options), where options define up to three functions: createHTML, createScript and createScriptURL. Any function you leave out cannot produce that type. The design goal is a small number of policies, each with one narrow job, kept in a reviewed module with code owners.

  • Sanitising HTML policy: createHTML passes input through a maintained sanitiser. MDN and web.dev both show DOMPurify; DOMPurify can return a TrustedHTML object directly when configured with RETURN_TRUSTED_TYPE. Pin and patch the sanitiser like any security dependency, because a sanitiser bug becomes an XSS bug.
  • Escaping policy: for text that should never contain markup, escape the five HTML special characters. Better still, refactor the call site to use textContent and remove the need for a policy at all.
  • Script URL policy: createScriptURL parses the input with the URL constructor and returns it only if the origin and path match a fixed allow-list (for example your own CDN path for lazily loaded bundles). Return null or throw for anything else.
  • Script policy: most applications need none. If a legacy component requires createScript, limit it to exact, known strings and plan its removal.
  • Never a pass-through: a policy whose function returns its input unchanged converts any string into a trusted value and defeats enforcement. Treat a pass-through policy as a vulnerability in review, with one exception: content that is a compile-time constant, documented as such.
  • Keep policy objects private: do not export a policy object globally. Export narrow helper functions instead, so other modules cannot call createHTML with arbitrary input.

The default policy

A policy named default is special. When enforcement is on and code passes a string to a sink, the browser calls the default policy with that string and uses the result. If the default policy returns null or undefined, the assignment throws a TypeError. MDN recommends using it only while transitioning legacy code, and web.dev calls it a last resort. A safe default policy logs the call site, sanitises HTML, and refuses script and script URL conversions, so legacy code fails closed rather than open.

Framework and library policies

Frameworks that write to the DOM need their own policies listed in trusted-types. Angular, for example, documents the policies angular (its own reviewed code), angular#bundler (CLI lazy chunks), angular#unsafe-bypass (needed only if the app calls DomSanitizer bypass methods such as bypassSecurityTrustHtml), angular#unsafe-jit and angular#unsafe-upgrade, and gives trusted-types angular; require-trusted-types-for 'script'; as a baseline header. The names containing unsafe are a useful audit signal: each one you add is a documented relaxation. See the Angular Security Guide and, for React's dangerouslySetInnerHTML escape hatch, the React and Next.js Security Guide.

Browser support and the tinyfill

MDN browser compatibility data (checked 27 October 2026) records TrustedTypePolicyFactory support from Chrome 83 (and Chromium-based Edge), Firefox 148 and Safari 26. Older browsers still in your user base will not enforce the directives and simply ignore them.

MDN describes a one-line "tinyfill" for unsupported browsers: if trustedTypes is undefined, define createPolicy to return the options object it was given. Policy functions then return sanitised strings instead of typed objects. The logic is that enforcement in supporting browsers forces every call site through a policy; the same code paths then run through the same sanitisers in browsers that do not enforce. The protection in older browsers therefore depends on your testing having happened under enforcement. Make sure CI and end-to-end tests run in a browser that enforces Trusted Types, with the enforcing header set, or the tinyfill gives you nothing.

SituationRecommended approachTrade-off
New application or greenfield componentEnforce from day one with named policies and no default policySmall upfront design effort; lowest long-term cost
Large legacy single-page applicationReport-only, then a logging default policy, then refactor per module, then remove the default policyMonths of work; the default policy is a temporary risk you must track
Heavy third-party script use (tag managers, widgets)Inventory which vendors hit sinks via violation reports; isolate or replace those that cannot complySome vendors may block enforcement; isolation in a sandboxed iframe can help
Small team, simple sitePrefer refactoring to safe sinks and the HTML Sanitizer API setHTML(); use Trusted Types enforcement with trusted-types 'none' where no HTML writing is neededVery little policy code to maintain

Rolling out Trusted Types in a large application

  1. Set up report collection. Deploy a report endpoint (web.dev mentions collectors such as reporting-api-processor and go-csp-collector) or listen for securitypolicyviolation events and use a ReportingObserver in test builds.
  2. Send report-only on the pages you are migrating. For example Content-Security-Policy-Report-Only: require-trusted-types-for 'script'; report-to csp-endpoint. Nothing breaks; every string reaching a sink is reported.
  3. Run static checks in parallel. Reports only show code that actually ran. Static tools find the rest: Mozilla's eslint-plugin-no-unsanitized flags assignments to innerHTML and calls such as insertAdjacentHTML without an escaping function, and Google's tsec wraps the TypeScript compiler to flag string use of Trusted Types sinks.
  4. Fix by category. In order of preference: rewrite to a safe sink (textContent, DOM construction, setAttribute on non-dangerous attributes), use a library that is already Trusted Types compatible, route through a named policy, and only as a last resort let the default policy handle it.
  5. Add a temporary default policy that logs a structured event (call site, sink, first characters) and sanitises HTML while refusing script conversions. Track the count of default policy invocations as your burn-down metric.
  6. Add the trusted-types allow-list in report-only, listing every policy that should exist. Unknown names in reports mean code or a library is creating policies you did not plan for.
  7. Enforce on a pilot. Switch the header to Content-Security-Policy for a percentage of traffic or one route, watch error telemetry for TypeError spikes, then widen.
  8. Remove the default policy once its invocation count is zero across a full release cycle.
  9. Rollback plan: keep the header in configuration (edge, CDN or reverse proxy), not compiled into the application, so a failed enforcement can drop back to report-only within minutes without a code release.

Detection and measurement

Trusted Types reports are one of the few security signals that point straight at a line of code. MDN describes the violation report fields; the sample usually holds the first 40 characters of the offending value, and web.dev shows Trusted Types reports with a blocked URL of trusted-types-sink, a violated-directive of require-trusted-types-for, a source file, line and column, and a sample that starts with the sink name.

SignalWhere it comes fromWhat it tells you
Sink violations (trusted-types-sink)CSP reports, report-only or enforcedA string reached a sink: refactoring backlog in report-only, blocked attempt or regression when enforced
Policy creation violationstrusted-types allow-listUnexpected code, a new library or injected script tried to create a policy
Default policy invocationsYour own logging inside the default policyRemaining legacy call sites
Front-end TypeError rateClient error monitoringUser-facing breakage after enforcement
Policy code changesCode owners and review recordsChanges to the security-critical surface

Watch enforced-mode sink violations from production carefully. A sudden cluster from a single page with unusual samples can indicate an attempted injection that the browser blocked, which is worth correlating with web application firewall and server logs.

Metrics that show the control is working:

  • Percentage of routes or documents served with enforcing Trusted Types headers.
  • Number of distinct sink violation locations in report-only, trending to zero.
  • Default policy invocations per day, trending to zero, then the default policy removed.
  • Number of policies and of relaxations (wildcards, 'allow-duplicates', framework unsafe policies) in the allow-list.
  • Count of DOM XSS findings from testing and bug bounty before and after enforcement.
  • Time from a new violation location appearing to its fix.

Where it fits in frameworks and standards

FrameworkReferenceRelevance
OWASP ASVS 5.0V3.4.3 (CSP header limiting execution of malicious JavaScript), V3.4.7 (CSP violation reporting location), V1.3.1 (sanitise untrusted HTML with a well-known library), V1.3.2 (avoid eval() and dynamic code execution)Trusted Types is a strong way to evidence these on the client side
MITRE CAPECCAPEC-588 DOM-Based XSS; CAPEC-63 Cross-Site ScriptingThe attack patterns the control targets
MITRE ATT&CKT1059.007 Command and Scripting Interpreter: JavaScriptScript execution that DOM XSS enables in the browser
NIST SP 800-53 Rev. 5SI-10 Information Input Validation; SA-8 Security and Privacy Engineering Principles; SA-11 Developer Testing and Evaluation; SA-15 Development Process, Standards, and ToolsInput handling, secure design, testing under enforcement and tooling such as linters
NIST CSF 2.0PR.PS-06 Secure software development practices are integrated and monitoredTrusted Types as a secure development practice with measurable outcomes

Common failure patterns

  • Report-only forever: teams collect reports for months but never enforce, so the control protects nobody. Set an enforcement date per route when the migration starts.
  • A pass-through default policy: a default policy that returns its input unchanged makes every violation disappear and every sink open again. Review the default policy like authentication code.
  • Wildcard or duplicate-friendly allow-lists: trusted-types * or 'allow-duplicates' added to silence a library error lets any script create a policy with a trusted name.
  • Exported policy objects: a policy exported as a global utility becomes a universal converter that any module, or injected script, can call.
  • Unpatched sanitisers: a pinned, years-old sanitiser behind createHTML carries its own bypasses. Trusted Types proves the sanitiser ran, not that it was right.
  • Testing without enforcement: relying on the tinyfill while CI runs in a browser or configuration without the enforcing header leaves new string sinks undetected until production.

Practitioner checklist

  • Inventory DOM sinks in your code and third-party scripts using report-only violations plus eslint-plugin-no-unsanitized or tsec.
  • Define a small set of named policies in a reviewed module with code owners; no pass-through functions.
  • Prefer safe sinks such as textContent and the HTML Sanitizer API setHTML() over policies where possible.
  • Deploy require-trusted-types-for 'script' and a named trusted-types allow-list in report-only, with a reporting endpoint.
  • Use a default policy only as a logging, fail-closed migration aid, and track its invocations to zero.
  • List framework policies explicitly and treat any unsafe framework policy as a documented exception.
  • Run end-to-end tests in an enforcing browser with the enforcing header set.
  • Deliver the header from edge or proxy configuration so you can roll back to report-only quickly.
  • Alert on policy creation violations and on clusters of enforced sink violations in production.

Standards and references

Related NHI Mgmt Group resources: Cross-Site Scripting (XSS) Prevention Guide · Content Security Policy Guide · Third-Party JavaScript Management Guide · TypeScript and JavaScript Secure Coding Guide · Permissions Policy, COOP, COEP and CORP Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 27 October 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.