← Back to JavaScript, page 4

javascript-0070 · Medium mid

How can tagged templates be used to build safe, readable helpers such as parameterized queries and dedented text?

A tag function receives the fixed text pieces and the interpolated values separately, so it can treat values as data and never splice them into the text. This makes parameterized SQL builders, escaping helpers, and dedent utilities possible with plain template syntax. The pieces array is frozen, has a raw version, and is the same object for each evaluation of one call site.

Full answer

A tagged template calls a function with strings (an array of the literal pieces) followed by each interpolated value as separate arguments. The function decides what to do with them and can return any value, not only text.

The safest use is a query builder. Instead of joining user input into the SQL string, the tag places a placeholder such as $1 where each value was, and returns the text and the values separately. The database driver then sends them apart, so input is never parsed as SQL. The code reads like a normal template, yet injection is not possible through the interpolated values. The same approach works for escaping HTML, as in the earlier example, and for building shell arguments.

Another use is formatting. A dedent tag removes the shared indentation from a multi-line template, which keeps embedded text tidy in indented code. String.raw and strings.raw provide the unprocessed source text, useful for regular expressions and file paths.

Properties worth knowing: strings is frozen, and strings.raw is a parallel array. For one call site in the source, the engine passes the same strings object every time, which lets a library cache work done on the template. For a${1}b, strings has one more entry than the values.

A tag can also compose nested results. A sql tag can accept another sql fragment as a value and merge its text and values, so conditions can be assembled safely.

Tags do not make unsafe output safe automatically. The author of the tag defines the behavior.

javascript
function sql(strings, ...values) {
  let text = '';
  const params = [];
  strings.forEach((piece, i) => {
    text += piece;
    if (i >= values.length) return;
    const value = values[i];
    if (value && value.isSql) {
      text += value.text.replace(/\$(\d+)/g, (_, n) => `$${Number(n) + params.length}`);
      params.push(...value.params);
    } else {
      params.push(value);
      text += `$${params.length}`;
    }
  });
  return { text, params, isSql: true };
}

const name = "Robert'); DROP TABLE students;--";
const minMarks = 40;
const query = sql`SELECT * FROM students WHERE name = ${name} AND marks >= ${minMarks}`;
console.log(query.text);
console.log(query.params);

const onlyActive = sql`active = ${true}`;
const combined = sql`SELECT id FROM users WHERE city = ${'Pune'} AND ${onlyActive}`;
console.log(combined.text, combined.params);

function dedent(strings, ...values) {
  const full = strings.reduce((out, piece, i) => out + piece + (i < values.length ? values[i] : ''), '');
  const lines = full.replace(/^\n/, '').split('\n');
  const indent = Math.min(...lines.filter((l) => l.trim()).map((l) => l.match(/^ */)[0].length));
  return lines.map((l) => l.slice(indent)).join('\n').trimEnd();
}
const message = dedent`
    Dear ${'Asha'},
      your marks are ${88}.
    Regards`;
console.log(message);

function inspect(strings) {
  return { frozen: Object.isFrozen(strings), raw: strings.raw[0], cooked: strings[0] };
}
console.log(inspect`line\none`);

const sites = [];
function remember(strings) {
  sites.push(strings);
}
for (let i = 0; i < 2; i++) remember`same call site ${i}`;
remember`same call site ${0}`;
console.log(sites[0] === sites[1], sites[0] === sites[2]);

Run with Node.js v24.22.1 as js-70.js; two runs gave identical output. Output: SELECT * FROM students WHERE name = $1 AND marks >= $2 [ "Robert'); DROP TABLE students;--", 40 ] SELECT id FROM users WHERE city = $1 AND active = $2 [ 'Pune', true ] Dear Asha, your marks are 88. Regards { frozen: true, raw: 'line\\none', cooked: 'line\none' } true false

Key points

  • A tag receives literal pieces and values separately and may return anything.
  • A sql tag turns values into placeholders, preventing injection through interpolated values.
  • dedent and String.raw are formatting uses.
  • strings is frozen and is the same object for each evaluation of one call site.
  • Nested fragments need the tag to merge their text and values.

Common mistakes

  • Concatenating values into the SQL text inside the tag, which brings back injection.
  • Assuming a tagged template is automatically safe; the tag decides.
  • Forgetting that strings has one more element than the values.
  • Using cooked strings where the raw source text is needed, such as regex or path sources.

Follow-ups

  • How would a tag return a function or an object rather than a string?
  • Why does the engine give the same strings object for each evaluation of a call site?
  • How would you write an html tag that escapes values but accepts trusted nested html fragments?

Tips

  • Use the parameterized query as the headline example; it is the one with real security value.
  • Mention that strings is frozen and cached per call site for libraries that cache.
  • Say that the tag author is responsible for safety.