Concepts 🚀 Project 🧮 Labs
📚 Learn / Security / Cross-site scripting (XSS) defence

Cross-site scripting (XSS) defence

Always escape user content before inserting into HTML. escapeHtml() is your best friend.

Code example

function escapeHtml(s) {
  return String(s)
    .replace(/&/g,'&')
    .replace(/</g,'&lt;')
    .replace(/>/g,'&gt;')
    .replace(/"/g,'&quot;')
    .replace(/'/g,'&#39;')
    .replace(/`/g,'&#96;');  // crucial for template literals
}

How it works

XSS is when attacker-controlled HTML/JS runs in another user's browser. The defence: convert <, >, &, ', ", and ` to HTML entities before inserting user content into innerHTML. The ` character is often forgotten — but it's critical because it terminates JS template literals, which can crash the whole script block (the bug we just fixed in notebook.html). The notebook, competition detail, and realtime templates all use escapeHtml() now. Jinja2's {{ var }} auto-escapes by default; only innerHTML assignments in JS need manual escaping.

🔍 Where this is used in OpenBenchML templates/notebook.html, competition_detail.html, realtime.html — escapeHtml() on every user-controlled interpolation.