javascript / expert
Snippet
Defensive Programming with Tagged Templates
Tagged templates allow intercepting template literal processing. This 'Expert' pattern is crucial for building Domain Specific Languages (DSLs) or security layers that automatically sanitize inputs before they reach sensitive sinks like HTML or SQL.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
function safeHTML(strings, ...values) {return strings.reduce((acc, str, i) => {const val = String(values[i] || '').replace(/[&<>"]/g, c => ({'&':'&','<':'<','>':'>','"':'"'}[c]));return acc + str + val;}, '');}const userInput = '<img src=x onerror=alert(1)>';const message = safeHTML`<div>User says: ${userInput}</div>`;console.log(message);
nodejs
Breakdown
1
function safeHTML(strings, ...values)
A tag function that receives raw string fragments and the interpolated values separately.
2
values[i].replace(/[&<>"]/g, ...)
Aggressively escapes special characters within the values to prevent injection attacks.
3
safeHTML`... ${userInput}`
Invokes the sanitizer tag, ensuring the resulting string is safe for rendering.