Tagged template literal with XSS protection for untrusted content.

Security: Escapes &, <, >, ", ' to prevent script injection, tag injection, and attribute injection attacks.

Performance: Same optimizations as html with additional escaping step. Use html for trusted content to avoid escape overhead.

Critical for: User input, form data, API responses, comments, any external content.

const userInput = '<script>alert("XSS")</script>';
safeHtml`<p>${userInput}</p>`
// "<p>&lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;</p>"
const users = [{name: '<script>', email: 'user@test.com'}];
safeHtml`<table>${users.map(u => safeHtml`<tr><td>${u.name}</td></tr>`)}</table>`
// Escapes user.name, keeps structure safe
  • Parameters

    • strings: TemplateStringsArray

      Static template parts

    • Rest...values: any

      Dynamic values for interpolation and escaping

    Returns string

    Rendered HTML with escaped dynamic content