HTML template tag with auto-escaping for JavaScript
npm install @remix-run/html-templateSafe HTML template tag with auto-escaping for JavaScript.
html-template provides a tagged template literal for safely constructing HTML strings with automatic escaping of interpolated values to prevent XSS vulnerabilities.
- Automatic HTML escaping - All interpolated values are escaped by default
- Explicit raw HTML - Use html.raw when you need unescaped HTML from trusted sources
- Composable - SafeHtml values can be nested without double-escaping
- Type-safe - Full TypeScript support with branded types
- Zero dependencies - Lightweight and self-contained
- Runtime agnostic - Works in Node.js, Bun, Deno, browsers, and edge runtimes
Install from npm:
``sh`
npm install @remix-run/html-template
`ts
import { html } from '@remix-run/html-template'
let userInput = ''
let greeting = html
console.log(String(greeting))
// Output:
Hello <script>alert("XSS")</script>!
`By default, all interpolated values are automatically escaped to prevent XSS attacks.
If you have trusted HTML that should not be escaped, use
html.raw:`ts
import { html } from '@remix-run/html-template'let trustedIcon = ''
let button = html.raw
console.log(String(button))
// =>
`Warning: Only use
html.raw with content you trust. Never use it with user input.$3
SafeHtml values can be nested without double-escaping:
`ts
import { html } from '@remix-run/html-template'let title = html
let content = htmlSome content with ${userInput}
let page = html
`$3
You can interpolate arrays of values, which will be flattened and joined:
`ts
import { html } from '@remix-run/html-template'let items = ['Apple', 'Banana', 'Cherry']
let list = html
- ${item}
)}
`$3
Use
null or undefined to render nothing:`ts
import { html } from '@remix-run/html-template'let showError = false
let errorMessage = 'Something went wrong'
let page = html
${errorMessage} : null}
`Related Packages
@remix-run/fetch-router` - HTTP router that works great with html-templateSee LICENSE