Sub topic 15
Pitfalls and Limitations
This chapter assumes you have already written the html and sql tags from earlier chapters. It also assumes you know about cooked versus raw strings and about member tags. Tagged templates are a small feature, but a handful of mistakes come up again and again. Most of them happen because a tag looks like a string while it actually behaves like a function call.
Treating Escaped Values as Safe Everywhere
An escaping tag protects one context: HTML text and quoted attribute values. It does nothing for URLs, inline scripts, CSS, or unquoted attributes. The escaped string below is still dangerous:
const escapeHTML = (value) => String(value)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
function html(strings, ...values) {
return strings.reduce(( + escapeHTML(values[i - 1]) + str);
}
const url = 'javascript:alert(1)';
console.log(html`<a href="${url}">profile</a>`);
// '<a href="javascript:alert(1)">profile</a>' : nothing needed escapingThe tag only trusts the static parts that the developer wrote. That trust is correct. It does not follow that every value becomes safe in every position. Validate URLs and similar inputs separately, or use a library such as lit that knows the context of each binding.
Double Escaping Nested Templates
A simple html tag returns a plain string. If you nest one call inside another, the outer call escapes the inner markup:
const item = html`<li>${'a & b'}</li>`;
console.log(html`<ul>${item}</ul>`);
// '<ul><li>a & b</li></ul>'The fix is to return a marker object. The tag then passes those objects through unchanged:
class SafeHTML {
constructor(value) { this.value = value; }
toString() { return this.value; }
}
function safeHtml(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 li = safeHtml`<li>${'a & b'}</li>`;
console.log(String(safeHtml`<ul>${li}</ul>`));
// '<ul><li>a & b</li></ul>'Syntax Traps
Optional chaining cannot be used as a tag. obj?.tag followed by a template literal is a SyntaxError, so guard the call with an if statement instead.
A template literal on the line after an expression does not trigger automatic semicolon insertion. JavaScript reads the two lines as a single tagged call:
const greet = () => 'tagged!';
const msg = greet
`hello`;
console.log(msg); // 'tagged!', not a function followed by a stringInvalid Escapes Turn into undefined
In a tagged template, a sequence such as \unicode sets the cooked string to undefined instead of throwing. A tag that concatenates strings[i] will then silently print the text "undefined". If your tag can receive arbitrary text such as LaTeX or Windows paths, read strings.raw. Without a tag, the same literal is still a SyntaxError.
Quick Reference
| Pitfall | Symptom | Fix |
|---|---|---|
| Context-blind escaping | `javascript:` URLs pass through unchanged | Validate per context |
| Nested string returns | Visible `<li>` in the output | Return a marker type |
| `?.` before a tag | `SyntaxError` | Use an explicit guard |
| Template on the next line | Unexpected function call | End the previous line with `;` |
| Invalid escape | The text "undefined" in the output | Use `strings.raw` |
Exercise
A tag is defined as const t = (s, ...v) => s.join('|');. What does `ta\xzz${1}b ` return, and why?
Show answer
It returns 'undefined|b'. \xzz is an invalid escape, so the cooked s[0] is undefined. join turns undefined into an empty string, so the result is actually '|b'. Using s.raw.join('|') would give 'a\\xzz|b'.
Exercise
Why does const x = log followed by a newline and ` ready call log`?
Show answer
A template literal can continue an expression, so automatic semicolon insertion does not fire. JavaScript parses the two lines as `logready `, which is a tagged template call.