Hiprup

What is XSS and how do you prevent it?

XSS (Cross-Site Scripting) is an attack where malicious scripts are injected into a page and run in other users' browsers, stealing data or hijacking sessions.

  • Escape output — render user content as text, not HTML (use textContent, not innerHTML).

  • Sanitize — clean any HTML you must render with a trusted library such as DOMPurify.

  • Content Security Policy — a CSP header blocks unauthorised scripts as a strong backstop.

  • HttpOnly cookies — keep auth tokens unreadable by JavaScript.

Golden rule: never trust user input — treat it as untrusted both when it comes in and when it goes out.

// VULNERABLE: innerHTML with user input
const userInput = '<img src=x onerror=alert("XSS")>';
document.getElementById('output').innerHTML = userInput; // Executes the script!

// SAFE: textContent (no HTML parsing)
document.getElementById('output').textContent = userInput; // Shows as plain text

// SAFE: Sanitize with DOMPurify
import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(userInput);
document.getElementById('output').innerHTML = clean; // Safe HTML

// SAFE: Escape function
function escapeHtml(str) {
  const div = document.createElement('div');
  div.textContent = str;
  return div.innerHTML;
}
console.log(escapeHtml('<script>alert(1)</script>'));
// '&lt;script&gt;alert(1)&lt;/script&gt;'

// CSP Header (server-side)
// Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.com

innerHTML renders the malicious img tag, triggering onerror (XSS). textContent displays it as plain text (safe). DOMPurify strips dangerous HTML while preserving safe formatting.

The escape function converts special characters to HTML entities. CSP headers restrict which scripts can execute on the page.

Show the attack (innerHTML with user input) and multiple defenses: textContent, DOMPurify, escapeHtml, and CSP. Know all three XSS types (stored, reflected, DOM-based).

React auto-escaping (dangerouslySetInnerHTML is the exception) shows framework awareness.

What is XSS and how do you prevent it? | Hiprup