Course contentsShow
← Security
Lesson 1050 of 3,05222. Web Security - Client-Side and SPA SecurityFree lesson

Trusted Types API

Discover how Trusted Types enforce type-safe DOM manipulation to eliminate DOM-based XSS at the API level.

Trusted Types API

You'll learn how Trusted Types enforce compile-time safety for DOM manipulation, eliminating entire classes of DOM-based XSS vulnerabilities.

What Are Trusted Types?

Trusted Types is a browser API that prevents DOM-based XSS by enforcing type-safe DOM manipulation. Instead of allowing arbitrary strings to flow into dangerous DOM sinks (like innerHTML, eval(), or document.write()), Trusted Types requires developers to explicitly create "trusted" objects that the browser verifies before insertion.

Think of it like a security checkpoint at a building entrance: instead of letting anyone walk in with any package, you require all packages to go through scanning and receive a "verified" stamp before entering.

How It Works

When Trusted Types is enabled via CSP (require-trusted-types-for 'script'), the browser blocks raw string assignments to risky DOM APIs. Instead, you must:

  1. Create a Trusted Type policy (a function that sanitizes/validates input)
  2. Use that policy to generate trusted objects (TrustedHTML, TrustedScript, TrustedScriptURL)
  3. Only these trusted objects can be assigned to dangerous sinks

This shifts XSS prevention from runtime filtering to API-level enforcement—the browser itself rejects unsafe data at the source.

The Security Guarantee

Unlike Content Security Policy or Subresource Integrity (which control where code comes from), Trusted Types controls what flows through your code. Even if an attacker finds an injection point, they cannot execute XSS because the browser refuses untrusted strings in DOM sinks. It's defense-in-depth that catches vulnerabilities before they execute.

Key Takeaway:
Trusted Types eliminate DOM-based XSS by making the browser reject raw strings in dangerous APIs, requiring developers to explicitly validate all dynamic content through type-checked policies.