Skip to content
jshacks.dev
Security

Use Trusted Types to block DOM XSS

Create a Trusted Types policy so sinks like innerHTML reject raw strings, which blocks DOM XSS in Chrome and Edge 83+ and Safari 26+.

1 min read
Summarize in AI

A single el.innerHTML = userInput is enough for DOM XSS. Trusted Types makes the browser refuse plain strings at such sinks, so every injection point has to go through a policy you wrote and can review.

http
Content-Security-Policy: require-trusted-types-for 'script'; trusted-types app-html
app.jsJavaScript
const policy = trustedTypes.createPolicy('app-html', {
  createHTML: (input) => DOMPurify.sanitize(input),
});

const box = document.querySelector('#comment');
box.innerHTML = policy.createHTML(userComment); // allowed
box.innerHTML = userComment; // TypeError
Text
TypeError: Failed to set the 'innerHTML' property on 'Element': This document requires 'TrustedHTML' assignment.

The require-trusted-types-for 'script' directive turns innerHTML, outerHTML, document.write and eval into sinks that only accept TrustedHTML, TrustedScript or TrustedScriptURL objects. The trusted-types directive lists the policy names that may exist, so a library cannot quietly create its own. Your audit shrinks to the body of createHTML. See the MDN Trusted Types API page.

Firefox did not enforce Trusted Types at the time of writing, so treat it as defence in depth next to escaping and a sanitizer, and ship it first with Content-Security-Policy-Report-Only to find the sinks you forgot.

Also inBrowser
Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.