Render server data safely

Treat all data as text. Only use innerHTML with HTML you escaped yourself.

AJAX · Render server data safelyAdvanced
const escapeHTML = (s) => String(s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));

function commentHTML(c) {
  return '<article><h4>' + escapeHTML(c.author) + '</h4><p>' + escapeHTML(c.text) + '</p></article>';
}

fetch('/api/comments').then(r => r.json()).then(data => {
  document.getElementById('comments').innerHTML = (data.items || []).map(i => commentHTML({ author: 'User ' + i, text: '<script>alert(1)</script>' })).join('');
});
xsssecuritytextContentescape