Skip to content
jshacks.dev
Fundamentals

Use a tagged template to build safe HTML

Build HTML with a tagged template that escapes every interpolated value, so a comment containing markup is shown as text. Node.js 24.

2 min read
Summarize in AI

A template literal inserts whatever you give it, so <p>${comment}</p> turns a user's comment into live markup. A tagged template can escape each value before it is inserted, and Node.js 24 runs this one as written.

JavaScript
const escapeHtml = (value) =>
  String(value).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);

function html(strings, ...values) {
  return strings.reduce((out, chunk, i) => out + chunk + (i < values.length ? escapeHtml(values[i]) : ''), '');
}

const comment = '<img src=x onerror="steal()">';

console.log(html`<p class="comment">${comment}</p>`);
console.log(`<p class="comment">${comment}</p>`);
console.log(html`<p>${1 + 1} &amp; ${'a & b'}</p>`);
Text
<p class="comment">&#60;img src=x onerror=&#34;steal()&#34;&#62;</p>
<p class="comment"><img src=x onerror="steal()"></p>
<p>2 &amp; a &#38; b</p>

A tag is a function called with the literal chunks and the values separately. The html tag in the example leaves the chunks alone, since you wrote them, and escapes each value, so the onerror payload prints as &#60;img src=x onerror=&#34;steal()&#34;&#62; and the browser shows it as text. The plain template on the second line writes the markup as it is. The last line shows the split: the &amp; you typed stays, while the & in the value becomes &#38;. The call form is in the specification for tagged templates.

This escapes for text content and quoted attributes only. It does not make a value safe inside a script block, an unquoted attribute, a style rule or a javascript: URL, and for those you need a different escape, or a templating library with context awareness. If your framework already escapes output, such as React, you do not need this.

Taggednode 24
Share

More snippets

Fundamentals

Sort dates in an array

Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.

1 min read
Fundamentals

Sort by multiple keys

Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.

1 min read
Fundamentals

Get a random item from an array

Pick a random item from an array with Math.random, and see why rounding the index instead of flooring it makes the middle item twice as likely. Node.js 18.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.