Configuring Content Security Policy (Part 8): Trusted Types and DOM XSS
Use Trusted Types with CSP to lock down dangerous DOM injection sinks such as innerHTML. Learn require-trusted-types-for, trusted-types policies, report-only migration and framework integration.

A strict Content Security Policy makes it much harder for injected markup to execute arbitrary JavaScript.
Trusted Types attacks the same XSS problem from another direction.
Instead of asking only which scripts are allowed to execute, Trusted Types asks:
which parts of the application are allowed to create values that reach dangerous DOM injection APIs?
That is a powerful distinction.
A large frontend might contain hundreds of places where strings move through the application, but only a handful of places where code actually writes HTML into innerHTML, assigns a script URL, calls insertAdjacentHTML() or otherwise crosses a browser injection boundary.
Trusted Types lets the browser enforce that those sinks receive specially created typed values instead of ordinary strings.
And in 2026 this is no longer a Chrome-only curiosity: MDN marks the key CSP directives as newly available in the Baseline 2026 set across current browser versions, while still warning that older clients may not support them.
DOM XSS is different from server-reflected XSS
Classic XSS examples often look like this:
request parameter
│
▼
server builds unsafe HTML
│
▼
browser executes injected code
DOM-based XSS can happen entirely in the browser:
attacker-controlled URL/storage/message
│
▼
JavaScript reads string
│
▼
application writes it into dangerous DOM API
│
▼
browser interprets it as HTML/script
For example:
const message = new URLSearchParams(location.search).get('message');
document.getElementById('output').innerHTML = message;
If message is attacker-controlled, assigning it directly to innerHTML can turn data into markup.
A strong script-src may limit exploitability, but the unsafe DOM pattern still exists.
Trusted Types targets that pattern directly.
The central idea: dangerous sinks stop accepting ordinary strings
With enforcement enabled:
Content-Security-Policy:
require-trusted-types-for 'script'
certain DOM XSS injection sinks no longer accept arbitrary strings.
Code such as:
element.innerHTML = userInput;
can fail because userInput is a plain string.
Instead, the application must create an appropriate Trusted Type value through an approved policy:
const policy = trustedTypes.createPolicy('app-html', {
createHTML: input => sanitizeHtml(input)
});
const trusted = policy.createHTML(userInput);
element.innerHTML = trusted;
Now the dangerous operation is concentrated around one explicit transformation function.
That is the real benefit: the browser turns an invisible trust assumption into an enforceable API boundary.
Trusted Types do not magically sanitise anything
This is the most important warning in the entire article.
This policy is useless:
const policy = trustedTypes.createPolicy('app-html', {
createHTML: input => input
});
You have created a TrustedHTML factory that declares every string safe without checking it.
Trusted Types enforce where trust decisions happen.
They do not decide whether your decision is sensible.
A secure policy might use a well-reviewed sanitizer:
const policy = trustedTypes.createPolicy('app-html', {
createHTML: input => DOMPurify.sanitize(input)
});
The exact sanitizer depends on the application and required HTML features, but the principle remains:
Untrusted string
│
▼
Small reviewed policy
│
├── validate/sanitise
▼
TrustedHTML
│
▼
DOM injection sink
The name require-trusted-types-for 'script' is slightly confusing
You might expect this directive to affect only <script> tags.
It does more than that.
The current Trusted Types specification defines the 'script' sink group to cover DOM XSS injection sinks associated with script-capable HTML and related APIs.
That includes dangerous operations such as HTML injection, not merely assigning JavaScript source code.
Think of the keyword as the standards-defined sink group, not as “only scripts”.
What kinds of sinks are we worried about?
The exact standards list evolves, but the common mental model includes APIs capable of turning strings into executable/interpreted browser content.
Examples you should investigate include:
element.innerHTML = value;
element.outerHTML = value;
element.insertAdjacentHTML('beforeend', value);
and script/resource-oriented sinks depending on the Trusted Type involved.
The safest application code often avoids these APIs completely when simple DOM operations will do.
Instead of:
container.innerHTML = `<span>${name}</span>`;
prefer:
const span = document.createElement('span');
span.textContent = name;
container.replaceChildren(span);
No HTML parsing is required, so there is no HTML injection problem to solve.
Trusted Types should not become an excuse to use unsafe sinks everywhere.
There are several Trusted Type value classes
The platform defines typed values for different kinds of dangerous operations.
The key conceptual types include:
TrustedHTML
TrustedScript
TrustedScriptURL
A policy exposes corresponding creation functions when needed:
trustedTypes.createPolicy('app', {
createHTML(value) {
return sanitize(value);
},
createScript(value) {
return validateScript(value);
},
createScriptURL(value) {
return validateScriptUrl(value);
}
});
In most applications, you should be very reluctant to create arbitrary TrustedScript values at runtime.
If application data is regularly being converted into executable JavaScript strings, step back and question the architecture.
trusted-types controls which policy names may exist
require-trusted-types-for turns on enforcement at sinks.
The trusted-types CSP directive controls which Trusted Type policies the page is allowed to create.
For example:
Content-Security-Policy:
require-trusted-types-for 'script';
trusted-types app-html analytics-adapter
Now JavaScript may create only policies with approved names such as:
trustedTypes.createPolicy('app-html', ...)
and:
trustedTypes.createPolicy('analytics-adapter', ...)
Trying to create:
trustedTypes.createPolicy('just-trust-everything', ...)
is blocked.
That dramatically improves auditability.
Without policy-name restrictions, any library on the page could potentially create a new permissive policy and undermine your intended trust model.
Do not allow * unless you genuinely mean it
A policy such as:
trusted-types *
allows arbitrary Trusted Type policy names.
That may be convenient during migration, but it weakens one of the strongest governance benefits of the feature.
Your production goal should usually be a small named set:
trusted-types app-html framework-policy
Then each policy represents a known piece of code with a defined reason to exist.
'none' is the strict end state for applications that need no policies
If the application can completely avoid relevant injection sinks, the specification supports preventing policy creation entirely:
trusted-types 'none';
require-trusted-types-for 'script'
Now dangerous sinks require Trusted Type values, but the page cannot create any policy values itself.
That is extremely restrictive and will not fit many rich applications, but it illustrates the model nicely:
the best injection sink is often the one your application does not need.
Default policies are migration tools, not ideal architecture
Trusted Types supports a special policy named default.
When enforcement encounters an ordinary string at a protected sink, a default policy can transform it instead of the browser immediately rejecting it.
For example:
trustedTypes.createPolicy('default', {
createHTML: input => DOMPurify.sanitize(input)
});
This can make migration dramatically easier in a large legacy application.
But be careful.
A global default sanitizer can hide where unsafe sinks exist because old code continues working automatically.
The stronger long-term model is:
explicit dangerous operation
│
▼
explicit named policy
│
▼
reviewable trust transformation
Use a default policy to gain visibility and migrate safely, then reduce dependence on it where practical.
Report-only mode makes Trusted Types deployable
Just like ordinary CSP, Trusted Types enforcement can be evaluated through:
Content-Security-Policy-Report-Only:
require-trusted-types-for 'script';
trusted-types app-html default;
report-to csp
This is invaluable on an existing frontend.
You can discover which parts of the application would fail before you block them.
The reports can identify Trusted Types sink violations, helping you find dangerous DOM operations that static grep may miss in bundled/minified/runtime paths.
A sensible migration starts there.
Step 1: inventory dangerous DOM operations
Search the codebase for patterns such as:
.innerHTML
.outerHTML
insertAdjacentHTML
DOMParser
createContextualFragment
script.src assignments
setAttribute on dangerous targets
framework raw-HTML escape hatches
Do not assume every match is vulnerable.
Classify them.
For each sink, ask:
Is this sink necessary?
Where does the value originate?
Can attacker-controlled data reach it?
Can normal DOM APIs replace it?
If HTML is required, how is it sanitised?
Who should own the Trusted Type policy?
That is already a useful security review even before enforcement.
Step 2: remove sinks that do not need to exist
Suppose code does this:
message.innerHTML = `Saved ${filename}`;
Nothing here requires HTML parsing.
Replace it with:
message.textContent = `Saved ${filename}`;
No policy. No sanitizer. No TrustedHTML. Less attack surface.
This is better than creating a Trusted Types policy to preserve an unnecessary unsafe coding pattern.
Step 3: centralise genuinely required HTML sanitisation
Some applications intentionally display user-authored rich text, Markdown output, CMS blocks or email previews.
Those do need HTML.
Create one reviewed path:
const richTextPolicy = trustedTypes.createPolicy('rich-text', {
createHTML(input) {
return DOMPurify.sanitize(input, {
// application-specific allowed markup
});
}
});
Then:
preview.innerHTML = richTextPolicy.createHTML(renderedHtml);
Now code review has a clear place to inspect:
Who can generate TrustedHTML?
What sanitisation rules apply?
Where is it used?
A sanitizer must match the context
Do not assume “sanitised” is a universal property.
An HTML sanitizer produces content appropriate for HTML parsing under its configured rules.
It does not automatically make the same string safe as:
- a JavaScript program;
- a CSS expression;
- a URL;
- SQL;
- a shell command.
Trusted Type creation functions map trust to specific browser sink categories, which helps stop these contexts being casually conflated.
React: raw HTML is the obvious boundary
React’s normal JSX interpolation escapes strings:
<div>{userInput}</div>
The obvious HTML escape hatch is:
<div dangerouslySetInnerHTML={{ __html: html }} />
When introducing Trusted Types, treat each dangerouslySetInnerHTML use as an intentional review point.
If a library or framework layer currently expects a plain string, you may need an adapter during migration.
Do not simply wrap every string in a policy that returns it unchanged.
That converts a useful browser enforcement mechanism into type theatre.
Vue: v-html is the comparable review point
Vue escapes ordinary template interpolation.
v-html deliberately renders HTML:
<div v-html="html"></div>
Vue’s own security model expects developers not to use untrusted content there unsafely.
A Trusted Types rollout gives you another mechanism for controlling raw DOM injection, but framework/library compatibility must be tested against your exact Vue version and rendering setup.
Even before enforcement, audit every v-html usage and ask whether HTML is actually required.
Angular already leans into Trusted Types
Angular’s current security documentation strongly recommends Trusted Types as an additional DOM-level XSS defence.
Angular defines several policy names for framework functionality depending on which features you use, including policies for core Angular behaviour and optional policies for bundling, JIT or explicit security bypasses.
A minimal Angular-oriented header can look conceptually like:
Content-Security-Policy:
trusted-types angular;
require-trusted-types-for 'script'
If the application uses other Angular features, official documentation identifies additional policy names that may be required.
This is an important lesson: do not invent policy names for framework internals when the framework documents its own Trusted Types contract.
Angular bypass APIs should stand out even more under Trusted Types
If your application uses methods such as:
bypassSecurityTrustHtml
bypassSecurityTrustResourceUrl
those are explicit security decisions.
Angular documents a separate Trusted Types policy name for applications using unsafe-bypass functionality.
That is useful because the CSP itself can expose the fact that your application relies on bypass paths.
Treat adding that policy as a trigger to review every bypass call.
Third-party libraries are the migration pain point
A library written before Trusted Types may do this internally:
tooltip.innerHTML = template;
Once enforcement begins, that library may break even if your application code is clean.
Your options include:
- upgrade to a Trusted Types-compatible version;
- configure the library’s official policy integration;
- replace it;
- wrap a narrowly reviewed adapter;
- temporarily use a controlled default policy;
- keep enforcement in report-only while migration continues.
Do not create one giant “third-party” policy that blindly trusts every string from every dependency.
That moves the original problem behind a nicer API.
Policy count should stay small
It is tempting to create a policy for every component:
modal-html
profile-html
tooltip-html
cms-html
admin-html
markdown-html
legacy-html
Sometimes different sanitisation rules genuinely justify separate policies.
Often this just creates complexity.
Prefer policies around distinct trust semantics, for example:
rich-text -> sanitised user/CMS HTML
static-template -> fixed application-owned fragments
vendor-widget -> narrowly validated vendor URL
A policy name should tell a reviewer what kind of trust decision it represents.
TrustedScript should be extremely rare
If you find yourself designing:
createScript(input) {
return input;
}
stop.
Turning strings into JavaScript at runtime is exactly the behaviour modern web architecture should usually eliminate.
Prefer:
- imported modules;
- normal functions;
- declarative configuration;
- data structures;
- precompiled templates.
A TrustedScript policy is not a safe version of eval() by default.
It is a mechanism for the rare cases where you have an auditable reason to create executable script text.
TrustedScriptURL needs URL validation, not HTML sanitisation
A script URL policy might look like:
const scripts = trustedTypes.createPolicy('approved-scripts', {
createScriptURL(input) {
const url = new URL(input, location.origin);
if (url.origin !== location.origin) {
throw new TypeError('Unapproved script origin');
}
return url.href;
}
});
That policy expresses a real trust rule:
script URLs must resolve to our origin
A policy that simply returns any URL string is not meaningful validation.
CSP still matters after Trusted Types
Trusted Types and strict CSP protect different stages.
A simplified model:
Attacker-controlled string
│
▼
Trusted Types
prevents string entering dangerous sink
│
▼
DOM/script created
│
▼
CSP
constrains whether resulting code/resource may execute/load
Use both where appropriate.
Trusted Types does not replace:
script-src 'nonce-{NONCE}' 'strict-dynamic'
and CSP does not replace safe DOM construction.
Browser compatibility needs a graceful strategy
As of 2026, modern browser support has improved enough for MDN to classify both require-trusted-types-for and trusted-types as Baseline 2026/newly available.
Older browsers may still ignore the directives/API.
That makes Trusted Types a good progressive security control:
Modern browser -> browser-enforced sink typing
Older browser -> application sanitisation + CSP still protect as designed
Do not weaken your sanitizer or output-encoding practices because the browser now supports Trusted Types.
The code must remain secure when enforcement is unavailable.
Browser security is strongest when the layers agree
Trusted Types protects dangerous DOM sinks; CSP constrains execution and resources. SiteTidy can help verify that the CSP layer is actually present in the public response after your deployment pipeline and CDN have finished with it.
A practical migration using report-only
For an established application, a sensible sequence is:
1. Inventory injection sinks
2. Remove sinks that can use safe DOM APIs
3. Introduce sanitizer/validation policies for genuine sinks
4. Restrict allowed Trusted Type policy names
5. Add Report-Only require-trusted-types-for
6. Collect sink violation reports
7. Fix framework/third-party incompatibilities
8. Exercise critical user journeys
9. Enforce for modern browsers
10. Keep reports and code-review rules in place
That turns a potentially disruptive browser feature into a controlled refactoring programme.
Example report-only header
A migration policy might look like:
Content-Security-Policy-Report-Only:
require-trusted-types-for 'script';
trusted-types app-html rich-text default;
report-to csp
At this stage, the default policy may exist to keep legacy code functioning while reporting tells you where strings still reach protected sinks.
Later, you can work toward:
Content-Security-Policy:
require-trusted-types-for 'script';
trusted-types app-html rich-text
with no catch-all default conversion.
Combine Trusted Types reporting with source maps
Violation reports become much more useful if you can map production bundle locations back to source code.
A report pointing to:
app.8fe2c.js:1:483299
is technically precise but unpleasant to debug.
Your internal observability pipeline can use privately stored source maps to resolve the location to:
src/components/RichTextPreview.tsx:84
Do not necessarily publish source maps openly solely for this purpose. Keep them in your error-monitoring/build pipeline where appropriate.
Add a lint/code-review rule for sinks
Browser enforcement catches runtime behaviour.
Preventive engineering can stop new sink usage earlier.
Consider:
- ESLint rules that flag direct
innerHTML/dangerous DOM APIs; - framework-specific security linting;
- code review requirements around raw HTML APIs;
- wrappers that expose only approved Trusted Types policies;
- tests that run with Trusted Types enforcement enabled.
Make the safe path easier than the bypass path.
Test the sanitizer, not only the policy
If your security now depends on:
richTextPolicy.createHTML(input)
that policy deserves real tests.
Include hostile inputs such as:
<img src=x onerror=alert(1)>
<script>alert(1)</script>
<a href="javascript:alert(1)">click</a>
<svg onload=alert(1)></svg>
The exact attack corpus depends on your sanitizer and allowed HTML model.
Use maintained security test cases rather than assuming one obvious <script> example proves the sanitizer is safe.
Do not write your own HTML sanitizer casually
HTML parsing and browser behaviour contain a large number of edge cases.
A few regex replacements such as:
html.replace(/<script.*?>.*?<\/script>/gi, '')
are not a robust sanitizer.
Use a mature, maintained sanitizer appropriate to your platform and configure it with the narrowest markup your product needs.
Trusted Types makes the sanitizer central; that is exactly why it needs to be good.
Treat policy creation like a privileged API
A useful code organisation is to put Trusted Type policy creation in a small security module:
src/security/trustedTypes.ts
rather than scattering calls to:
trustedTypes.createPolicy(...)
throughout the application.
Then application code imports safe functions such as:
renderSanitisedRichText(value)
approvedScriptUrl(url)
The lower-level policy objects remain hard to misuse.
A Trusted Types review checklist
Before enforcement, verify:
[ ] Raw DOM injection sinks inventoried
[ ] Unnecessary sinks replaced with textContent/DOM APIs
[ ] Sanitizer is maintained and tested
[ ] Trusted Type policies have meaningful names
[ ] CSP trusted-types allowlist is narrow
[ ] Default policy is temporary/intentional
[ ] Third-party libraries tested under enforcement
[ ] Framework-documented policy names included where required
[ ] Report-only sink violations triaged
[ ] Source maps/debug tooling can locate production violations
[ ] Older browsers remain secure without Trusted Types support
[ ] Strict script CSP remains in place
Final thought
Trusted Types changes a difficult security question:
“Can any attacker-controlled string somewhere in this enormous frontend eventually reach a dangerous DOM API?”
into a smaller one:
“Which few functions are allowed to manufacture trusted values for those APIs, and are those functions correct?”
That is a much more reviewable security boundary.
It does not eliminate the need for sanitisation, framework safety, output encoding or strict CSP. It makes those controls easier to organise around the places where strings become executable browser behaviour.
In Part 9, we will switch from design to diagnosis: a hands-on guide to debugging CSP failures from browser console messages and violation reports — including inline script errors, nonce mismatches, strict-dynamic surprises, blocked API calls, duplicate policies, CDN header conflicts and the production-only failures that waste the most time.
