Sub topic 15
Pitfalls and Limitations
This chapter assumes you have read the earlier chapters. It builds on the html and sql tags, the strings/values split, cooked and raw strings, and call-site caching. Each pitfall below comes from something earlier chapters introduced as a feature.
Where Things Go Wrong
A tagged template passes through several stages before it produces a result, and each stage has its own failure mode.
Pitfall: Treating Escaped Values as Safe Everywhere
The escapeHTML function from the HTML chapter replaces &, <, >, " and '. That protects text content and attribute values inside quotes. It does not protect every place a value can land.
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 url = 'javascript:alert(1)';
console.log(html`<a href="${url}">link</a>`);
// '<a href="javascript:alert(1)">link</a>' (script runs on click)
const cls = 'x onmouseover=alert(1)';
console.log(html`<div class=${cls}></div>`);
// '<div class=x onmouseover=alert(1)></div>' (new attribute injected)Neither payload contains a character that escapeHTML touches. The tag cannot see where in the markup each value will end up, because it treats every slot the same way. Output is unsafe in these places:
| Position of `${}` | Why entity escaping fails | What to do instead |
|---|---|---|
| Unquoted attribute | Spaces end the attribute and start a new one | Always quote attributes in the static parts |
| `href`, `src`, `action` | `javascript:` URLs contain no special characters | Validate the URL scheme against an allowlist |
| Inside `<script>` or `<style>` | Entity escaping does not apply in those contexts | Do not interpolate there; pass data via JSON in a data attribute |
| Event attribute such as `onclick` | The value is executed as JavaScript | Never interpolate |
| Tag or attribute name | Static structure becomes attacker-controlled | Never interpolate |
Libraries such as lit parse the static parts and know which context each slot sits in. A hand-written tag that only concatenates strings does not have that information.
Pitfall: Double Escaping When Templates Nest
The html tag returns a plain string. When you nest one result inside another, the outer call cannot tell trusted markup from user text, so it escapes the markup again:
const item = html`<li>${'a & b'}</li>`;
console.log(html`<ul>${item}</ul>`);
// '<ul><li>a &amp; b</li></ul>'The fix is to return a marker type, so the tag can recognize output it produced itself:
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>'Two related surprises remain. An array value becomes 'a,b', because String(['a', 'b']) joins with commas. A value of undefined or null prints as the word undefined or null. Real libraries handle arrays and nullish values explicitly. Your tag should handle them too, or document that it doesn't.
Pitfall: Seeding reduce with an Initial Value
The interleaving pattern only works because reduce runs without an initial value and starts from strings[0]. If you add '' out of habit, the indexes shift by one:
function broken(strings, ...values) {
return strings.reduce((out, str, i) => out + values[i - 1] + str, '');
}
console.log(broken`a${1}b`); // 'undefineda1b'On the first step i is 0, so values[-1] is undefined and gets stringified. An empty template such as ` broken also returns 'undefined'. Calling reduce without a seed is safe here because strings` always has at least one element.
Pitfall: Syntax Traps
Optional chaining cannot be a tag
const logger = maybeGetLogger();
logger?.tag`hello`; // SyntaxError: Invalid tagged template on optional chainThe language rejects this at parse time, so the whole script fails to load, not only that line. Any tag that includes ?. anywhere in its member chain is rejected the same way. Guard explicitly instead:
const result = logger && logger.tag ? logger.tag`hello` : undefined;Automatic semicolon insertion joins lines
A backtick at the start of a line continues the previous expression:
const unit = 'kg'
const text = 'weight'
`5 ${unit}`.lengthJavaScript reads the last two lines as ` const text = 'weight'5 ${unit}.length . That calls the string 'weight' as a tag and throws TypeError: "weight" is not a function`. If the previous line evaluates to a function, there is no error at all, and the function runs silently. Use semicolons, or put a semicolon at the start of any line that begins with a backtick.
Invalid escapes still break untagged templates
The relaxed rule for escapes such as \unicode applies only to tagged templates. The same text in an untagged literal is a SyntaxError. Inside a tag, the cooked part becomes undefined. Any tag that builds output from cooked strings will then print the word undefined:
const plain = (strings, ...values) =>
strings.reduce((out, str, i) => out + values[i - 1] + str);
console.log(plain`path \unicode here`); // 'undefined'If your tag might receive such input, check for undefined cooked parts and either throw a clear error or fall back to strings.raw.
String.raw cannot end with a backslash
console.log(String.raw`C:\temp\` + 'file');This line does not do what it looks like. ` \ ` escapes the closing backtick, so the literal keeps going, and the line fails to parse. Write the trailing backslash outside the template: String.rawC:\temp + '\\' `.
Limitation: Substitutions Are Evaluated Eagerly
Every ${} expression is evaluated, from left to right, before the tag body runs. A tag cannot skip one. A debug tag therefore pays the full cost even when logging is off:
let enabled = false;
const debug = (strings, ...values) =>
enabled ? String.raw(strings, ...values) : undefined;
function expensive() { console.log('computed'); return 42; }
debug`value=${expensive()}`; // prints 'computed' even though nothing is loggedIf you need lazy behavior, pass functions (` ${() => expensive()} `) and have the tag call them only when needed.
Limitation: Static Parts Are Fixed in Source
Only substitution slots can vary. Everything else is fixed when the code is written. That has three consequences.
- SQL identifiers cannot be parameters. `
sqlSELECT FROM ${table}producesSELECT FROM $1`, and the database rejects a placeholder in that position. Table and column names need a separate helper that checks them against an allowlist. Don't concatenate them into the query. - You cannot load a template from a file. A string read at runtime is not source code. You can call a tag directly with a fake array, as in
tag(Object.assign(['a', 'b'], { raw: ['a', 'b'] }), 1), but that array is new on every call. Caches keyed on call-site identity will then miss every time and grow without limit, and some libraries reject arrays that did not come from a real template. - The strings array is frozen. In strict mode, which includes all ES modules,
strings.push('x')orstrings[0] = 'y'throws aTypeError. Copy the array first with[...strings]if you need to change it.
Quick Reference
| Pitfall | Symptom | Fix |
|---|---|---|
| Context-blind escaping | XSS through `href` or unquoted attributes | Quote attributes, validate URLs, use a context-aware library |
| Nested string results | `&lt;` in output | Return a marker type and skip escaping for it |
| `reduce(..., '')` | Leading `undefined` | Omit the initial value |
| `obj?.tag` | Parse-time `SyntaxError` | Explicit guard |
| Line starting with a backtick | Unexpected call or `TypeError` | Semicolons |
| Invalid escape | Cooked part is `undefined` | Check, or use `strings.raw` |
| Eager substitutions | Wasted work | Pass functions |
| Dynamic identifiers | Database error or injection | Allowlist helper |
Exercise
A teammate's tag is const t = (s, ...v) => s.reduce((o, x, i) => o + v[i - 1] + x, '');. What does ` t${'A'}-${'B'} ` return, and what is the one-character-level fix?
Show answer
The strings array is ['', '-', ''], so the result is 'undefinedA-B'. On the first step i is 0 and v[-1] is undefined, which is stringified into the output. The fix is to remove the , '' initial value so reduce starts from s[0]. The result is then 'A-B'.
Exercise
Your html tag escapes all five special characters. Why is ` html<img src=${src}> ` still unsafe when src is 'x onerror=alert(1)', and what two changes would you make?
Show answer
The value contains no characters that the escaper changes. Because the attribute is unquoted, the space ends the src attribute and starts a new onerror attribute. First, quote the attribute in the static part: src="${src}". Second, validate src against allowed URL schemes such as https:, because a quoted attribute still accepts javascript: or data: URLs.
Exercise
Will config?.formattotal ${n}`` run if config exists, and how should it be written?
Show answer
It will not run. A tag with optional chaining is a SyntaxError at parse time, so the whole script fails to load whether or not config exists. Write an explicit guard instead: config && config.format ? config.formattotal ${n} : undefined. This also keeps this bound to config inside the tag.