Week 3 Summary - Understanding XSS and Safer DOM Practices

1. Concatenating HTML strings

  • Using APIs like innerHTML or building HTML with string concatenation is vulnerable to XSS.
  • If user input is injected directly into those strings, attackers can execute arbitrary JavaScript.

2. DOMPurify

  • A popular library for sanitizing HTML.
  • Very effective when you must allow arbitrary HTML input.
  • Not "perfect forever" — attackers constantly find new tricks, but the DOMPurify team is quick to patch.
  • Requires keeping dependencies up-to-date.

3. Safest approach

  • Constructing DOM nodes programmatically with document.createElement, setAttribute, and textContent is the most secure method.
  • This avoids mixing HTML structure with user data, making injection nearly impossible.
  • Downside: it’s more verbose and less developer-friendly.

4. Frameworks like React

  • Frameworks provide security and a nicer developer experience.
  • React and similar frameworks ultimately rely on DOM APIs to update the page, not on a sanitization library like DOMPurify