All topics
ES6+advanced

Tagged Template Literals for Safe HTML

Using tagged template functions to automatically escape interpolated values, a real-world defense against injection when building HTML or SQL strings dynamically.

Tagged template literals have one especially practical advanced use case worth calling out: automatically sanitizing interpolated values to prevent injection vulnerabilities when building HTML or SQL strings dynamically. This looks like a curiosity until you see the real security problem it solves.

A safe-HTML tag function is like a print shop that always runs your hand-written text through a content checker before merging it into a pre-approved letterhead template, but leaves the letterhead itself untouched.

Key Concepts

1
Recall that a tagged template calls its tag function with an array of literal string chunks and the interpolated expressions as separate arguments, rather than immediately concatenating everything. This separation is exactly what makes safe escaping possible: because the tag function receives interpolated values separately from the surrounding literal text, it can escape only the dynamic values while leaving the static template text untouched.
2
An html tag function can escape HTML-sensitive characters in every interpolated value before stitching the final string back together, meaning user-supplied data injected via ${userInput} gets automatically neutralized against XSS. This is the mechanism popular templating and CSS-in-JS libraries use internally, meaningfully safer than manually remembering to escape at every interpolation site.
3
The same pattern generalizes to any structured string format — a sql tag function could parameterize interpolated values instead of directly concatenating them, sidestepping SQL injection the same structural way.