Preventing XSS Attacks in JavaScript Applications

Cross-Site Scripting (XSS) remains one of the most common web vulnerabilities, and it almost always comes down to one root cause: untrusted data being inserted into the page as if it were trusted HTML.

// VULNERABLE: innerHTML executes any script tags in the input
element.innerHTML = userComment; // if userComment contains <script>, it runs

// SAFE: textContent never interprets its input as HTML
element.textContent = userComment;

// If you genuinely need to insert HTML, sanitize it first
import DOMPurify from 'dompurify';
element.innerHTML = DOMPurify.sanitize(userComment);

The Broader Pattern

  • Never use innerHTML, document.write(), or eval() with untrusted input
  • A Content Security Policy header adds a real second layer of defense even if a bug slips through
  • Framework template engines (React JSX, Vue templates) escape output by default — but their explicit “trust this raw HTML” escape hatches (dangerouslySetInnerHTML, v-html) reintroduce the exact same risk if used carelessly