Overview
Trusted Types is a security mechanism in web browsers that helps prevent cross-site scripting (XSS) vulnerabilities by enforcing strict policies on how potentially dangerous content is handled. It restricts the use of unsafe APIs that accept untrusted input directly, such as innerHTML, outerHTML, and eval. Instead, it requires developers to explicitly define and use "trusted" values that have been validated or sanitized.
Trusted Types are particularly relevant in applications that dynamically render content from user input or third-party sources. By enforcing a strict policy, they ensure that only content that has been explicitly marked as safe can be used in contexts that could lead to XSS attacks. This mechanism is not a replacement for input sanitization or other security practices, but rather a complementary layer that adds an additional barrier against injection attacks.

Why It Matters
Trusted Types address a critical gap in traditional XSS prevention strategies. While sanitization and escaping are important, they can be bypassed or forgotten in complex applications. Trusted Types enforce a stricter separation between untrusted data and its usage in potentially dangerous contexts, making it significantly harder for attackers to inject malicious code. This is especially important in large-scale applications where maintaining consistent sanitization practices across all code paths is challenging.
For developers, Trusted Types offer a way to make their applications more robust by reducing the attack surface for XSS vulnerabilities. In production environments, this translates to fewer security incidents, reduced liability, and improved user trust. Additionally, Trusted Types can be enforced via Content Security Policy (CSP) directives, which can be configured to block execution of scripts when untrusted data is used in unsafe contexts.
How It Works
Trusted Types operate by introducing a new type system for strings in JavaScript. When a developer attempts to assign untrusted content to a dangerous property or function, the browser checks whether the content has been explicitly marked as "trusted." If not, the operation is blocked or throws an error, depending on the browser's enforcement mode.
- Trusted Types are defined using the
trustedTypes.createPolicy()API, which allows developers to define policies for specific contexts such as HTML insertion or script execution. - The policy defines how to process input data, such as sanitizing HTML or escaping dangerous characters before allowing it to be used in a dangerous context.
- When a policy is created, it can be applied to specific APIs like
Element.innerHTMLorHTMLScriptElement.srcto enforce safe usage. - Trusted Types can be used in conjunction with Content Security Policy (CSP) to provide layered defense against XSS attacks.
- Browser support for Trusted Types is available in modern browsers, including Chrome, Edge, and Safari, with some caveats for older versions.
Quick Reference
| Item | Purpose | Notes |
|---|---|---|
| trustedTypes.createPolicy() | Defines a policy for handling trusted content | Must be called before any trusted types are used |
| DOMString | Represents a string in the DOM | Used in APIs that accept potentially unsafe input |
| Element.innerHTML | Inserts HTML content into an element | Requires trusted types when enforced by CSP |
| HTMLScriptElement.src | Specifies a script source | Can be restricted to trusted URLs |
| Content Security Policy | Enforces trusted types | Requires CSP directives like trusted-types |
Basic Example
This example demonstrates how to create a simple Trusted Types policy that sanitizes HTML before allowing it to be used in an innerHTML assignment.
const policy = trustedTypes.createPolicy('defaultPolicy', {
createHTML: (string) => {
// Simple sanitization example
return string.replace(/<script>.*?<\/script>/gi, '');
}
});
const div = document.createElement('div');
div.innerHTML = policy.createHTML('<h1>Hello World</h1><script>alert("XSS")</script>');
The createPolicy function defines a policy named defaultPolicy with a createHTML function that removes script tags. The div.innerHTML assignment then uses the policy to sanitize the input before rendering.
Production Example
This example shows a more realistic implementation that includes validation, error handling, and a reusable policy for multiple DOM operations.
function createSecurePolicy() {
return trustedTypes.createPolicy('securePolicy', {
createHTML: (input) => {
if (typeof input !== 'string') {
throw new TypeError('Input must be a string');
}
// Sanitize input using DOMPurify or similar library
return DOMPurify.sanitize(input);
}
});
}
const policy = createSecurePolicy();
try {
const container = document.getElementById('content');
container.innerHTML = policy.createHTML(userInput);
} catch (error) {
console.error('Failed to apply trusted type:', error);
}
This version includes error handling, type checking, and integration with a sanitization library. It also demonstrates how policies can be reused across different parts of an application, making it more maintainable and secure.
Common Mistakes
- Not creating policies before using trusted types, which results in runtime errors or bypasses of the security mechanism.
- Using overly permissive sanitization rules that still allow dangerous content through, undermining the purpose of the mechanism.
- Ignoring browser support or CSP enforcement, leading to inconsistent behavior across environments.
- Not handling errors properly when policies fail, which can cause application crashes or unexpected behavior.
- Applying trusted types only to a subset of dangerous APIs, leaving gaps in protection.
Security And Production Notes
- Trusted Types are not a silver bullet and must be combined with other security practices like input validation and output encoding.
- Enforcement of Trusted Types can be configured via CSP, which should be tested in all environments to ensure consistent behavior.
- Browser support is good in modern browsers, but older browsers may not support Trusted Types at all, requiring fallback strategies.
- Performance impact is minimal, but the overhead of sanitization should be considered in high-throughput applications.
- Trusted Types policies should be reviewed regularly for potential bypasses or outdated sanitization logic.
Related Concepts
Trusted Types are closely related to several other security and development concepts:
- Content Security Policy (CSP): Trusted Types are enforced via CSP directives, making them a key part of a comprehensive security strategy.
- Input Sanitization: Trusted Types complement sanitization by providing a stricter framework for handling untrusted data.
- DOMPurify: A popular library for sanitizing HTML, often used in Trusted Types policies to ensure safe content.
- HTML Injection: Trusted Types are specifically designed to prevent this type of vulnerability by restricting unsafe APIs.
- Security Headers: Trusted Types are part of a broader set of security headers and mechanisms that protect web applications.