12k
All articles

Blocking DOM XSS in React with Trusted Types

See how React 19.3 enables Trusted Types for DOM XSS protection, with a DOMPurify policy, CSP headers, and a safe report-only rollout for dangerouslySetInnerHTML.

OpenReplay Team
OpenReplay Team
Blocking DOM XSS in React with Trusted Types

React 19.3 passes Trusted Types objects straight to the DOM, so a React app can now enforce require-trusted-types-for 'script' and send all dangerouslySetInnerHTML markup through a DOMPurify-backed policy.

Until this release, that setup tended to fall apart. You sanitized your CMS HTML, turned on the CSP directive, and React converted your carefully typed value back into a string anyway.

This article covers the React change, the CSP headers, a policy module that also works in browsers without the API, and a rollout that starts in report-only mode. For the XSS basics, see preventing XSS in user-generated content.

Key Takeaways

  • Before React 19.3, React converted values to strings with '' + value, so a TrustedHTML object given to dangerouslySetInnerHTML reached innerHTML as a plain string, and an enforcing browser rejected it.
  • Under require-trusted-types-for 'script', assigning a plain string to an injection sink such as innerHTML throws a TypeError.
  • Trusted Types does not sanitize anything. It makes HTML reach the sink through a policy you wrote, and DOMPurify inside that policy does the cleaning.
  • Ship Content-Security-Policy-Report-Only first, fix every reported sink, allowlist your policy names with trusted-types, then enforce.
  • Browsers without Trusted Types enforce nothing, so the sanitizer inside your policy has to run on every call.

What Changed in React 19.3?

React 19.3 (released 9 September 2026) passes TrustedHTML, TrustedScript and TrustedScriptURL values to the DOM without coercing them. The browser can then check that a Trusted Types policy produced them.

Earlier versions stringified values with '' + value before handing them to DOM APIs. A TrustedHTML object passed to dangerouslySetInnerHTML therefore reached innerHTML as an ordinary string, and an enforcing browser refused it. The release post uses innerHTML as its example sink, and dangerouslySetInnerHTML, which writes innerHTML, now preserves the trusted object. The same release also made Fragment refs stable.

How Do Trusted Types Block DOM XSS?

The Trusted Types API closes injection sinks to raw strings. Once it is enforced, sinks such as innerHTML or a script’s src accept only typed objects created by a named policy.

Trusted typeSink categoryExample sink
TrustedHTMLHTML parsingElement.innerHTML
TrustedScriptScript texteval()
TrustedScriptURLScript loadingHTMLScriptElement.src

Trusted Types does not clean any markup itself. What it guarantees is that every value at a sink went through a policy function, and that function is where DOMPurify does the work. This changes the security model. Sanitization stops being something every developer has to remember at every call site and becomes something the browser enforces.

Setting the Content-Security-Policy Header

Trusted Types is switched on with the require-trusted-types-for 'script' CSP directive. Start by sending that directive in Content-Security-Policy-Report-Only. In that mode the browser reports violations but still lets the code run.

Content-Security-Policy-Report-Only: require-trusted-types-for 'script'

Add a reporting endpoint using the report-to directive so the browser sends each violating sink to your collector rather than only logging it in the console. Once the reports stop, switch to the enforcing header:

Content-Security-Policy: require-trusted-types-for 'script'; trusted-types app-html

require-trusted-types-for makes string assignments to sinks throw. trusted-types lists the policy names that are allowed, and trustedTypes.createPolicy() throws if you call it with a name that isn’t on the list. Send them as response headers. Browsers don’t support the report-only header or the report-to directive in a <meta> tag.

Creating a Policy That Wraps DOMPurify

In a React app, create the Trusted Types policy once, at module scope, and import it wherever you need it. createPolicy() throws a TypeError on a duplicate name unless 'allow-duplicates' is in the trusted-types directive. That makes a component body the wrong place for it, because React re-renders components and StrictMode double-invokes them.

// trusted-html.js
import DOMPurify from 'dompurify';

const factory = globalThis.trustedTypes ?? {
  createPolicy: (name, rules) => rules,
};

export const htmlPolicy = factory.createPolicy('app-html', {
  createHTML: (dirty) =>
    DOMPurify.sanitize(dirty, { TRUSTED_TYPES_POLICY: null }),
});

createHTML returns a sanitized string and the browser wraps it in TrustedHTML. Passing TRUSTED_TYPES_POLICY: null stops DOMPurify from creating its own internal dompurify policy, so the allowlist only needs app-html. Don’t put RETURN_TRUSTED_TYPE: true inside createHTML, because the callback must return a plain string.

The fallback object applies MDN’s tinyfill idea in a form suited to ES modules. Where the API is missing, createPolicy returns your rules object unchanged, so htmlPolicy.createHTML() still runs DOMPurify and gives back a string. The code path is the same everywhere. Because the fallback is local, the module also imports without errors during server rendering, where trustedTypes is undefined. DOMPurify needs a DOM implementation to sanitize on the server, and its README covers that setup.

DOMPurify also offers a shortcut: call DOMPurify.sanitize(dirty, { RETURN_TRUSTED_TYPE: true }) with no policy of your own. It returns TrustedHTML where supported, and you add dompurify to the allowlist (trusted-types app-html dompurify).

Using the Policy with dangerouslySetInnerHTML

With React 19.3 or later, put the policy’s output in __html and React passes the TrustedHTML object to innerHTML unchanged.

// Before: under enforcement, the raw string throws a TypeError
<div dangerouslySetInnerHTML={{ __html: html }} />

In report-only mode, that line shows up as a violation report. In enforcing mode, it throws.

import { htmlPolicy } from './trusted-html';

export function RichText({ html }) {
  return <div dangerouslySetInnerHTML={{ __html: htmlPolicy.createHTML(html) }} />;
}

Route all CMS, markdown and rich-text output through RichText (or a direct htmlPolicy.createHTML() call). If you later grep for __html:, every match should be next to a policy call.

Rolling Out Trusted Types Safely

A safe Trusted Types rollout has four stages: report only, fix every reported sink, allowlist your policy names, then enforce.

  1. Deploy Content-Security-Policy-Report-Only: require-trusted-types-for 'script' with a reporting endpoint.
  2. Fix each reported sink by routing it through htmlPolicy, or replace it with a sink that doesn’t need trusted values, such as textContent.
  3. List every policy name your code and dependencies create in trusted-types.
  4. Switch to the enforcing Content-Security-Policy header.

If third-party code keeps assigning strings that you can’t fix yet, a policy named default can act as a temporary bridge. Under enforcement, the browser hands it every raw string that reaches a sink, and MDN recommends using it only while migrating legacy code.

// TEMPORARY: remove before you finish the migration.
import DOMPurify from 'dompurify';

if (globalThis.trustedTypes) {
  globalThis.trustedTypes.createPolicy('default', {
    createHTML(value) {
      console.warn('Untyped HTML reached a sink');
      return DOMPurify.sanitize(value, { TRUSTED_TYPES_POLICY: null });
    },
  });
}

The feature check keeps the module from throwing in browsers without the API and during server rendering.

Add default to trusted-types while this policy exists. Once its warnings stop appearing, remove both the policy and the allowlist entry.

What Happens in Browsers Without Trusted Types?

Browsers without Trusted Types don’t enforce anything. In those browsers, the sanitizer inside your policy is the only thing between untrusted HTML and the DOM. MDN marks window.trustedTypes as Baseline 2026, newly available since February 2026, so older browser versions in your traffic won’t have it.

The module-scope fallback handles this. Unsupported browsers ignore the header and still run DOMPurify.sanitize() on every call. For that reason, the policy must always sanitize and must never return its input unchanged.

Conclusion

React 19.3 removes the string coercion that used to break Trusted Types, so dangerouslySetInnerHTML can now carry policy-made HTML that the browser enforces. Ship the report-only header first, move every __html assignment onto one DOMPurify-backed policy, and enforce once the reports stop. Then apply the same discipline to the server side with these API security best practices.

FAQs

What happens if a Trusted Types default policy returns null or undefined?

The browser throws a TypeError at the sink and the assignment does not happen. A default policy that returns null or undefined is not a pass-through. It fails closed and blocks the write instead of letting the original string through. A default policy that returns null for every input is also a useful way to find leftover string assignments while you migrate.

Is it safe to use a wildcard or allow-duplicates in the trusted-types directive?

Neither is a good choice for production. A star (*) as a policy name allows any unique policy name, so injected script could register its own policy and create trusted values. The 'allow-duplicates' keyword lets code create several policies with the same name, so one name no longer maps to one known policy. List each exact policy name your code and dependencies create instead.

Can I still use eval() when Trusted Types is enforced?

Yes. Add the 'trusted-types-eval' keyword to your CSP. It allows eval() and similar functions only in browsers that support and enforce Trusted Types. Unlike 'unsafe-eval', it keeps those functions blocked in browsers without Trusted Types support. With enforcement on, the code passed to eval() still has to be a TrustedScript, or a raw string that a default policy turns into one. Otherwise the call throws.

DevTools for the frontend

Gain Debugging Superpowers

Unleash the power of session replay to reproduce bugs, track slowdowns and uncover frustrations in your app. Get complete visibility into your frontend with OpenReplay — the most advanced open-source session replay tool for developers.

Star on GitHub12k

We use cookies to improve your experience. By using our site, you accept cookies.