Web Security

XSS Prevention Guide

9 min read

Cross-Site Scripting (XSS) allows attackers to inject malicious scripts into web pages viewed by other users. It can steal cookies, capture keystrokes, and hijack sessions.

Types of XSS

Reflected XSS

Payload reflected from server in response. Requires victim to click malicious link.

<!-- Vulnerable -->
https://site.com/search?q=<script>alert(1)</script>

Stored XSS

Payload stored in database, executed when page loads. More dangerous - no user action needed.

DOM-based XSS

Payload executed entirely in browser via JavaScript DOM manipulation.

Prevention Techniques

1. Output Encoding

<!-- PHP -->
<?php echo htmlspecialchars($input, ENT_QUOTES, 'UTF-8'); ?>

<!-- JavaScript -->
element.textContent = userInput; // Safe
element.innerHTML = userInput;   // DANGEROUS

2. Content Security Policy (CSP)

Content-Security-Policy: 
  default-src 'self'; 
  script-src 'self' 'nonce-abc123';
  style-src 'self' 'unsafe-inline';

3. Use Secure Frameworks

React, Vue, Angular auto-escape by default. Use their built-in protections.

Defense in Depth

December 2024