Could someone briefly explain the practical advantage of Trusted Types in Content Security Policy compared with script hashes, nonces, and DOMPurify? Are Trusted Types mainly an additional security layer, or can they protect against situations that nonces and hashes do not? I understand that using textContent instead of innerHTML is generally safer, but I would like to understand what Trusted Types specifically add when handling JavaScript and injected HTML.
3 Answers
The protections are complementary: a nonce or hash says which inline or external scripts are allowed to run, while Trusted Types restrict how strings become HTML, script URLs, or other executable DOM content. Trusted Types cannot replace input validation, output encoding, or a sensible CSP, and they do not automatically make every operation safe. They reduce the chance that a DOM XSS bug turns into code execution by enforcing safer handling at the browser level.
Trusted Types are not really a stronger replacement for nonces or hashes; they protect a different part of the application. Nonces and hashes control which script elements may execute, while Trusted Types help prevent DOM-based XSS by requiring dangerous DOM sinks—such as innerHTML, outerHTML, insertAdjacentHTML, and some script-related APIs—to receive specially created Trusted Types objects instead of arbitrary strings. That enforcement happens in the browser, so an accidental unsafe assignment can be blocked before it becomes executable markup or script.
Think of Trusted Types as a defense-in-depth measure and a way to enforce secure coding practices across a codebase. DOMPurify can sanitize data, and avoiding innerHTML is good, but developers can still accidentally introduce an unsafe assignment later. A Trusted Types policy can make those assignments fail unless the value has passed through an approved policy, which is especially useful in large applications or when third-party code is involved. Nonces and hashes do not protect those DOM injection sinks because they mainly govern script loading or execution.

That makes sense. So the focus is the content being inserted into the DOM rather than authorizing a script itself. I already use DOMPurify where HTML is necessary and prefer textContent elsewhere, but now I understand what Trusted Types add.