Sub topic 8
Practical Pattern: An Auto-Escaping HTML Tag
This chapter assumes you know how a tag function receives its strings array and its values, and how reduce without an initial value interleaves them. Both were covered earlier. Here we use that pattern for a real job: building HTML from untrusted data without opening a cross-site scripting hole.
The Problem: Interpolation Is Injection
Cross-site scripting (XSS) happens when text supplied by a user ends up in a page as markup instead of as text. A plain template literal makes this easy to get wrong:
const comment = '<img src=x onerror="alert(document.cookie)">';
const markup = `<p class="comment">${comment}</p>`;
console.log(markup);
// <p class="comment"><img src=x onerror="alert(document.cookie)"></p>If markup is assigned to innerHTML, the browser creates an <img> element, the image fails to load, and the onerror handler runs attacker code.
A tagged template can fix this in a structural way. The tag gets the parts the developer wrote (the strings array) separately from the parts computed at runtime (the values). The static parts come from your source code, so they are trusted. The values may come from anywhere, so they are not. An HTML tag can pass the static parts through unchanged and escape every value.
Step 1: The Escape Function
Escaping replaces each character that has special meaning in HTML with its character reference, so the browser shows the character instead of parsing it.
| Character | Replacement | Why it must be escaped |
|---|---|---|
| `&` | `&` | Starts a character reference such as `<` |
| `<` | `<` | Opens a tag |
| `>` | `>` | Closes a tag; escaped for symmetry and older parsers |
| `"` | `"` | Ends a double-quoted attribute value |
| `'` | `'` | Ends a single-quoted attribute value |
const escapeHTML = (value) => String(value)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
console.log(escapeHTML('Tom & "Jerry" <3'));
// Tom & "Jerry" <3Step 2: The Minimal Tag
With the escape function in place, the tag uses the interleaving pattern and escapes only the values:
function html(strings, ...values) {
return strings.reduce((out, str, i) => out + escapeHTML(values[i - 1]) + str);
}
const user = '<img src=x onerror=alert(1)>';
console.log(html`<p>Hello, ${user}!</p>`);
// <p>Hello, <img src=x onerror=alert(1)>!</p>The <p> tags pass through because they belong to strings. The payload is neutralized because it arrived as a value. The developer doesn't have to remember to call escapeHTML at each interpolation site, because writing html in front of the literal is enough.
This version uses the cooked strings (strings), not strings.raw. That choice is correct here: if you write \n in an HTML template, you almost always want a real newline in the output.
Step 3: Handling Real-World Values
The minimal tag breaks down fast in real code. Three cases show up almost immediately.
- Missing values.
String(undefined)is'undefined', sohtml\<p>${user.nickname}</p>\`` prints the word "undefined" when there is no nickname. - Lists.
String(['a', 'b'])is'a,b', so mapping an array to markup leaves stray commas between the items. - Nesting. When one
htmlresult is interpolated into another, the inner markup is a plain string, so the outer tag escapes it again and the user sees<li>on the page.
The third case is the important one. The outer tag can't tell "a string that a trusted html call produced" from "a string a user typed". The fix is to give trusted output a distinct type. Then the tag can check that type instead of guessing from the string's contents.
const escapeHTML = (value) => String(value)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
class SafeHTML {
constructor(value) {
this.value = value;
}
toString() {
return this.value;
}
}
function renderValue(value) {
if (value instanceof SafeHTML) return value.value;
if (value == null || value === false) return '';
if (Array.isArray(value)) return value.map(renderValue).join('');
return escapeHTML(value);
}
function html(strings, ...values) {
const out = strings.reduce((acc, str, i) => acc + renderValue(values[i - 1]) + str);
return new SafeHTML(out);
}
// Explicit escape hatch for markup you have verified yourself.
const unsafeHTML = (markup) => new SafeHTML(String(markup));
const items = ['<b>bold?</b>', 'Tom & Jerry'];
const showBadge = false;
const page = html`
<ul>${items.map((item) => html`<li>${item}</li>`)}</ul>
${showBadge && html`<span class="badge">new</span>`}
<footer>${unsafeHTML('© 2026')}</footer>
`;
console.log(String(page));
// <ul><li><b>bold?</b></li><li>Tom & Jerry</li></ul>
// (empty line where the badge would be)
// <footer>© 2026</footer>Each case is handled by a deliberate choice:
SafeHTMLvalues are inserted as-is, because onlyhtmlandunsafeHTMLcreate them.null,undefined, andfalserender as nothing, which makescondition && html\...\`` work.- Arrays are rendered element by element and joined with no separator, and each element goes through the same rules.
- Everything else, including numbers and plain strings, is escaped.
The instanceof check trusts anything that is a SafeHTML. Keep the class private to your module so that other code can't create instances freely. Treat every call to unsafeHTML as something to check in code review.
Edge Cases Escaping Does Not Cover
Escaping the five characters makes a value safe inside element text and inside quoted attribute values. HTML has other contexts, and in some of them escaped text is still dangerous.
Unquoted attributes
const cls = 'x onmouseover=alert(1)';
console.log(String(html`<div class=${cls}>hi</div>`));
// <div class=x onmouseover=alert(1)>hi</div>The escape function never touches the space, so the value ends the attribute and starts a new one. The rule is simple: always quote attribute values in your templates. This rule applies to the static parts, so a linter or code review has to enforce it. The tag can't.
URL attributes
const link = 'javascript:alert(1)';
console.log(String(html`<a href="${link}">profile</a>`));
// <a href="javascript:alert(1)">profile</a>None of those characters need escaping, and clicking the link runs the script. Values in href, src, and action need a scheme check before they reach the tag:
function safeURL(value) {
try {
const url = new URL(String(value), 'https://example.invalid');
return ['http:', 'https:', 'mailto:'].includes(url.protocol) ? String(value) : '#';
} catch {
return '#';
}
}
console.log(safeURL('javascript:alert(1)')); // '#'
console.log(safeURL('/users/42')); // '/users/42'Script and style contents
Inside <script> and <style> elements the browser does not decode character references. <script>const n = "${name}";</script> turns a name like O'Brien into O'Brien in the JavaScript, so the data comes out wrong. Escaping also does nothing to stop JavaScript injection in this context. To pass data to a script, put JSON in a data- attribute (escaped as normal) or in a <script type="application/json"> block, and parse it.
| Context | Is the tag's escaping enough? | What to do |
|---|---|---|
| Element text | Yes | Nothing extra |
| Quoted attribute | Yes | Keep the quotes |
| Unquoted attribute | No | Always quote |
| `href` / `src` | No | Validate the scheme |
| `<script>` / `<style>` body | No | Pass data as JSON elsewhere |
| Event handler attribute (`onclick`) | No | Don't interpolate into it |
Libraries such as lit avoid many of these problems because they don't build strings at all. They parse the static parts once and bind values to specific DOM nodes and attributes. A later chapter covers that design. The string-building tag in this chapter suits server-side rendering, emails, and small scripts, as long as you respect the context limits above.
Exercise
With the minimal html tag from Step 2, what does html<p>${null}</p> return, and how does the Step 3 version change the result?
Show answer
The minimal tag returns '<p>null</p>', because String(null) is 'null' and escaping leaves it alone. The Step 3 version returns a SafeHTML object whose value is '<p></p>', because renderValue turns null into an empty string.
Exercise
A teammate makes escapeHTML replace the characters in this order: <, >, ", ', &. What does escapeHTML('<') return, and why?
Show answer
It returns '&lt;'. The first step turns '<' into '<', and the last step then turns that '&' into '&'. The browser displays the text '<' instead of '<'. The & replacement must run first.
Exercise
Why does the Step 3 tag return a SafeHTML object instead of a plain string, and what would break if it returned a string?
Show answer
A plain string can't be told apart from untrusted user input, so when one html result was interpolated into another, the outer tag would escape the inner markup again. The page would then show literal tags like <li>. The SafeHTML wrapper marks output as trusted, so renderValue can insert it unchanged.
Exercise
Is html<img src="${userUrl}"> safe with the Step 3 tag if userUrl is 'javascript:alert(1)'? How do you fix it?
Show answer
No. The value contains no characters that need escaping, so it is inserted unchanged and the dangerous scheme stays in the attribute. Pass the value through a scheme check such as safeURL(userUrl) first, which allows only http:, https:, and mailto: and falls back to '#'.