By Rahul — Google Frontend Engineer
The Attack in Simple Terms
XSS (Cross-Site Scripting) happens when an attacker injects malicious JavaScript into a web page that other users view. The script runs with the same privileges as the legitimate page — it can steal cookies, capture keystrokes, redirect users, or modify the page content.
Three Types of XSS
1. Stored XSS (Most Dangerous)
The malicious script is stored on the server (in a database, comment, profile). Every user who views the page is affected.
2. Reflected XSS
The malicious script is in the URL. The server includes it in the response without escaping.
3. DOM-based XSS
The vulnerability is entirely in client-side JavaScript. The server never sees the payload.
Prevention
1. Output Encoding (Most Important)
2. Content Security Policy (CSP)
3. Sanitize HTML When You Must Allow It
4. HttpOnly Cookies
React-Specific Concerns
dangerouslySetInnerHTML: Always sanitize with DOMPurify first- URL injection:
<a href={userInput}>— validate that it starts with https://, not javascript: - Server-side rendering: Ensure data is escaped before hydration
Summary
XSS injects malicious scripts into your page. Prevent it with output encoding (React does this by default), CSP headers, DOMPurify for HTML content, and HttpOnly cookies. Never use innerHTML with user input.