XSS

Cross-Site Scripting (XSS) is a security vulnerability that allows attackers to inject malicious scripts into web pages viewed by other users.

Overview

XSS is one of the most common web application vulnerabilities. It occurs when an application includes untrusted data in a web page without proper validation or escaping. Attackers can use XSS to steal cookies, session tokens, or other sensitive information, manipulate the DOM, or redirect users to malicious sites.

Example

javascript
// VULNERABLE CODE - DON'T DO THIS!
const userInput = '<script>alert("XSS")</script>';
element.innerHTML = userInput; // Dangerous!

// SAFE - Escape user input
const userInput = '<script>alert("XSS")</script>';
element.textContent = userInput; // Safe - treated as text

// SAFE - Use DOM methods
const p = document.createElement('p');
p.textContent = userInput;
element.appendChild(p);

// React (automatically escapes)
function UserProfile({ username }) {
  // Safe - React escapes by default
  return <div>Hello, {username}</div>;
}

// React UNSAFE usage
function DangerousComponent({ htmlString }) {
  // Dangerous! Only use with trusted content
  return (
    <div dangerouslySetInnerHTML={{ __html: htmlString }} />
  );
}

// Sanitizing HTML
import DOMPurify from 'dompurify';

function SafeHTML({ html }) {
  const clean = DOMPurify.sanitize(html);
  return <div dangerouslySetInnerHTML={{ __html: clean }} />;
}

// URL-based XSS prevention
const url = new URL(userInput, window.location.origin);
// Validate protocol
if (url.protocol === 'https:' || url.protocol === 'http:') {
  window.location = url.href;
}

// Preventing XSS in attributes
// BAD
const href = `javascript:alert('${userInput}')`;

// GOOD
const href = `/page?name=${encodeURIComponent(userInput)}`;

Types of XSS

Stored XSS:

  • Malicious script stored on server
  • Affects all users who view the data
  • Most dangerous type

Reflected XSS:

  • Script reflected from request to response
  • Requires victim to click malicious link
  • Common in search results

DOM-based XSS:

  • Vulnerability in client-side code
  • Never sent to server
  • Exploits unsafe JavaScript

Prevention

  • Escape user input before displaying
  • Use textContent instead of innerHTML
  • Implement Content Security Policy (CSP)
  • Validate and sanitize all input
  • Use frameworks that auto-escape (React, Vue)

Key Points

  • Common web security vulnerability
  • Allows injection of malicious scripts
  • Prevents: escape output, validate input
  • Modern frameworks help but aren't foolproof
  • Use Content Security Policy headers

Learn More