Sub topic 9
Building an Escaping Tag and Avoiding Injection
This chapter assumes you already know how tag functions receive their strings and values arguments, how nested template literals work, and how interpolated values are converted to strings. You should also be comfortable with reduce, map, join, and basic classes. Here we use those pieces to solve a real problem: inserting untrusted data into HTML (and SQL) without opening the door to injection.
Plain Interpolation Does Not Protect You
A template literal inserts each value exactly as its string conversion produces it. It does not know whether the result is going into HTML, a SQL query, a shell command, or a log line. It has no idea which characters are dangerous in those places.
const userName = '<img src=x onerror="alert(1)">';
const markup = `<p>Welcome, ${userName}!</p>`;
console.log(markup);
// <p>Welcome, <img src=x onerror="alert(1)">!</p>If markup is assigned to element.innerHTML, the browser parses the <img> tag. The image fails to load and the onerror handler runs. This is cross-site scripting (XSS): an attacker's text gets executed as code in someone else's page.
Template literals make string building easier to read, and that can make the problem harder to spot. Code like ` <p>${name}</p> ` looks clean and harmless. The fix is to put the escaping into the template itself, using a tag.
Where the Trust Boundary Sits
Tagged templates split a template neatly along trust lines:
- The
stringsarray holds the literal text written by the developer in the source file. It is trusted. - The
valuesarray holds the results of the${}expressions. These may come from anywhere, so treat them as untrusted.
An escaping tag uses that split. It copies the trusted strings through unchanged and escapes every value before joining.
A Minimal Escaping Tag
Here is the smallest useful version. It escapes the five characters that matter in HTML text content and in quoted attribute values.
function escapeHtml(value) {
return 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 userName = '<img src=x onerror="alert(1)">';
console.log(html`<p>Welcome, ${userName}!</p>`);
// <p>Welcome, <img src=x onerror="alert(1)">!</p>Several details matter here:
reduceis called without an initial value, sooutstarts asstrings[0]and the callback first runs withi = 1. That is why the value index isi - 1. The callback runs once per value, becausestringsalways has one more element thanvalues.&must be replaced first. If you replaced<first, you would produce<, and a later&replacement would turn it into&lt;, which is double-escaped.String(value)gives a predictable conversion for numbers,null, and objects with atoStringmethod.- The tag reads the cooked strings (
strings[i]), notstrings.raw. The developer wrote\nor\u00e9expecting it to be interpreted, so the cooked form is the right one.
Fixing Nesting: Marking Output as Safe
The minimal tag breaks as soon as you nest it. The inner html call returns a plain string, and the outer call cannot tell that string apart from user input, so it escapes it a second time.
function escapeHtml(value) {
return 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 items = ["a", "b"];
console.log(html`<ul>${items.map(item => html`<li>${item}</li>`).join("")}</ul>`);
// <ul><li>a</li><li>b</li></ul>You need a way to mark markup that has already been escaped. A small wrapper class does this. The tag returns a SafeHtml object. When it meets a SafeHtml value inside another template, it inserts it as is. It also handles arrays, so you no longer need the .join("") call.
class SafeHtml {
constructor(value) {
this.value = value;
}
toString() {
return this.value;
}
}
function escapeHtml(value) {
return String(value)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function render(value) {
if (value instanceof SafeHtml) return value.value;
if (Array.isArray(value)) return value.map(render).join("");
if (value === null || value === undefined || value === false) return "";
return escapeHtml(value);
}
function html(strings, ...values) {
let out = strings[0];
for (let i = 0; i < values.length; i++) {
out += render(values[i]) + strings[i + 1];
}
return new SafeHtml(out);
}
const items = ["Tea & cake", "<b>bold</b>"];
const showFooter = false;
const page = html`
<ul>${items.map(item => html`<li>${item}</li>`)}</ul>
${showFooter && html`<footer>Bye</footer>`}`;
console.log(String(page));
// (blank line)
// <ul><li>Tea & cake</li><li><b>bold</b></li></ul>
//The design choices behind this version:
- Arrays are rendered item by item. Each element still goes through
render, so an array of raw strings is escaped and an array ofSafeHtmlobjects is not. null,undefined, andfalserender as nothing. This makes${cond && html...}work without printing the wordfalse. Plain interpolation would print"false"or"null".toStringreturns the markup. Code that expects a string, such asString(page)orelement.innerHTML = page, gets the final HTML.- Only the tag creates
SafeHtml. If any code can writenew SafeHtml(userInput), the protection is gone. Some libraries keep the class private to the module, or offer a clearly named escape hatch such asunsafeHtml(str)so that bypasses are easy to find in code review.
Escaping Is Context-Specific
HTML escaping makes a value safe as text content and as the contents of a quoted attribute. It does not make a value safe everywhere in a document. The browser parses each location by different rules.
class SafeHtml {
constructor(value) { this.value = value; }
toString() { return this.value; }
}
function escapeHtml(value) {
return String(value)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function html(strings, ...values) {
let out = strings[0];
for (let i = 0; i < values.length; i++) {
out += (values[i] instanceof SafeHtml ? values[i].value : escapeHtml(values[i])) + strings[i + 1];
}
return new SafeHtml(out);
}
const url = "javascript:alert(1)";
console.log(String(html`<a href="${url}">profile</a>`));
// <a href="javascript:alert(1)">profile</a>
const cls = "x onclick=alert(1)";
console.log(String(html`<div class=${cls}>hi</div>`));
// <div class=x onclick=alert(1)>hi</div>Neither output changed, because none of the five escaped characters appear in the payloads. Both are still exploitable:
- The
javascript:URL runs code when someone clicks the link. URLs need validation of their scheme, not character escaping. - The unquoted attribute lets a space end the value and start a new attribute. Always quote attributes in your templates.
A scheme allowlist handles the URL case:
function safeUrl(input) {
try {
const parsed = new URL(input, "https://example.com");
return ["http:", "https:", "mailto:"].includes(parsed.protocol) ? input : "#";
} catch {
return "#";
}
}
console.log(safeUrl("javascript:alert(1)")); // #
console.log(safeUrl("/users/42")); // /users/42
console.log(safeUrl("https://example.org")); // https://example.orgYou then write html<a href="${safeUrl(url)}">profile</a>`. The tag still HTML-escapes the result, which is also needed because a URL can contain & or "`.
| Where the value lands | Is HTML escaping enough? | What to do |
|---|---|---|
| Element text: `<p>${x}</p>` | Yes | Escape |
| Quoted attribute: `title="${x}"` | Yes | Escape, always quote |
| Unquoted attribute: `class=${x}` | No | Add quotes in the template |
| URL attribute: `href="${x}"` | No | Allowlist schemes, then escape |
| Event handler: `onclick="${x}"` | No | Do not interpolate; attach listeners in JS |
| Inside `<script>` or `<style>` | No | Do not interpolate; pass data via `JSON` in a data attribute or a separate request |
| Tag or attribute name: `<${x}>` | No | Never interpolate; pick from a fixed list |
The Same Idea for SQL: Parameterize, Don't Escape
For SQL, the safest approach skips escaping entirely. You keep the values out of the query text and send them separately as parameters. A tag gives you the trusted/untrusted split you need for this.
function sql(strings, ...values) {
const text = strings.reduce((out, str, i) => out + "$" + i + str);
return { text, values };
}
const email = "x' OR '1'='1";
const minAge = 18;
const query = sql`SELECT * FROM users WHERE email = ${email} AND age >= ${minAge}`;
console.log(query.text);
// SELECT * FROM users WHERE email = $1 AND age >= $2
console.log(query.values);
// [ "x' OR '1'='1", 18 ]The { text, values } shape matches what PostgreSQL drivers such as pg accept in client.query(query). The database receives the attacker's string as data, so it can never become SQL syntax. Several real libraries work this way (for example postgres and sql-template-strings).
Parameters only work for values. Identifiers such as table or column names cannot be parameters, so pick them from a fixed allowlist in your code rather than interpolating them.
Common Mistakes
Building the string first, then tagging it. ` html${userTemplate} ` escapes the entire string, tags and all. That is safe but probably not what you wanted. The reverse mistake is worse: building with an untagged template and passing it to a sink.
const name = "<script>";
const unsafe = `<p>${name}</p>`; // untagged: nothing escaped
// element.innerHTML = unsafe; // XSS if name is attacker-controlledCalling the tag like a normal function. html("<p>" + name + "</p>") passes a plain string as strings. The loop then indexes characters of that string, and nothing is escaped. Linters and TypeScript types (TemplateStringsArray) can catch this.
Trusting the strings array from elsewhere. If you build a fake strings array from user input and call html(fakeStrings, ...), the "trusted" half is no longer trusted. Some libraries check Array.isArray(strings.raw) and that the array is frozen, which call-site template objects always are. This is a sanity check against accidental misuse. It does not stop a determined caller.
Forgetting that escaping is a one-way conversion. Escape once, at output time, as late as possible. If you store pre-escaped text in a database, it gets escaped again later or shows up as & in a plain-text email.
Exercise
Given the minimal html tag from this chapter (the one that escapes every value and returns a plain string), what does html<p title="${a}">${b}</p>` produce when a = 'He said "hi"' and b = "1 < 2 & 3"`? Is the result safe to assign to innerHTML?
Show answer
It produces <p title="He said "hi"">1 < 2 & 3</p>. It is safe: the value of a sits in a double-quoted attribute and b sits in element text, and HTML escaping covers both contexts.
Exercise
A teammate writes html<img src="${src}" ${attrs}>` and passes attrs = 'onerror="alert(1)"'`, expecting the tag to block the attack. Using the SafeHtml version of the tag, what is the output, and is it exploitable? How would you change the API?
Show answer
The output is <img src="..." onerror="alert(1)">. The quotes are escaped, but onerror= survives, so the browser sees an onerror attribute whose unquoted value is "alert(1)". That decodes to "alert(1)", a JavaScript string expression that does nothing, so this exact payload fails. A payload without quotes, such as onerror=alert(1), contains no escaped characters and does run. Interpolating attribute names is unsafe. Change the API to accept only a fixed set of attribute names (for example, an object whose keys are checked against an allowlist) and render each one as name="${escapedValue}".
Exercise
Extend the sql tag so that a value that is an array expands into a comma-separated list of placeholders, letting sqlSELECT FROM t WHERE id IN (${[4, 5, 6]})` produce text SELECT FROM t WHERE id IN ($1, $2, $3) with values [4, 5, 6]`.
Show answer
Keep a running parameter list and add placeholders as you go:
function sql(strings, ...values) {
const params = [];
const placeholder = (v) => { params.push(v); return "$" + params.length; };
let text = strings[0];
values.forEach((v, i) => {
text += (Array.isArray(v) ? v.map(placeholder).join(", ") : placeholder(v)) + strings[i + 1];
});
return { text, values: params };
}
Each array element becomes its own parameter, so the elements are still sent as data and never spliced into the SQL text. An empty array would produce IN (), which is invalid SQL, so a real version should reject or special-case it.