Sub topic 8
Practical Pattern: An Auto-Escaping HTML Tag
This chapter assumes you already know how a tag receives its strings array and values, and how reduce interleaves them to rebuild output. Here we use that pattern to fix a real security problem.
The problem with plain interpolation
Building HTML with an untagged template literal pastes values in exactly as they are. If a value comes from a user, that user can inject markup:
const user = '<img src=x onerror=alert(1)>';
const markup = `<p>Hello, ${user}!</p>`;
// '<p>Hello, <img src=x onerror=alert(1)>!</p>'If you assign markup to innerHTML, the browser runs the onerror handler. This is cross-site scripting (XSS).
A tag fixes this because it can tell the two kinds of input apart. The static strings were written by you in the source code, so they are trusted. The values are computed at runtime and may come from anywhere. The tag escapes only the values.
Writing the tag
const escapeHTML = (value) => String(value)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
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>'Because reduce has no initial value, it starts with strings[0], and the callback first runs with i = 1. So values[i - 1] always picks the value that sits between strings[i - 1] and strings[i].
Two details matter in escapeHTML:
&is replaced first. If it ran last, it would turn the<that was just produced into&lt;.- Quotes are escaped so that values stay safe inside quoted attributes, such as
title="${x}".
Allowing nested templates
The basic tag has a flaw: it escapes its own output when you nest one call inside another. The inner <li> would come out as <li>. A common fix is to wrap the result in a marker type that the tag trusts:
class SafeHTML {
constructor(value) { this.value = value; }
toString() { return this.value; }
}
function html(strings, ...values) {
const out = strings.reduce((acc, str, i) => {
const v = values[i - 1];
return acc + (v instanceof SafeHTML ? v.value : escapeHTML(v)) + str;
});
return new SafeHTML(out);
}
const item = '<b>milk</b>';
console.log(String(html`<ul>${html`<li>${item}</li>`}</ul>`));
// '<ul><li><b>milk</b></li></ul>'Only output produced by html itself skips escaping. A plain string can never get past it.
Where escaping is not enough
Entity escaping protects text content and quoted attribute values. It does not make every position safe:
| Context | Safe with this tag? | Why |
|---|---|---|
| `<p>${x}</p>` | Yes | `<` and `&` are neutralized |
| `title="${x}"` | Yes | Quotes are escaped |
| `title=${x}` (unquoted) | No | A space starts a new attribute |
| `href="${x}"` | No | `javascript:alert(1)` contains no special characters |
| `<script>${x}</script>` | No | Script content follows JavaScript rules, not HTML rules |
Exercise
What does html<p>${null}</p> produce with the first version of the tag, and why?
Show answer
It produces '<p>null</p>'. escapeHTML calls String(value), and String(null) is 'null'. If you want empty output, map null and undefined to '' before escaping.
Exercise
Why must the & replacement run before the others in escapeHTML?
Show answer
The other replacements insert entities that begin with &. If & were escaped afterward, < would become &lt; and the page would show the literal text "<" instead of "<".