Cross-Site Scripting (XSS) Attacks
Learn the interview-ready mental model, practical trade-offs, and production patterns for this web fundamentals topic.
Topic content
Cross-Site Scripting (XSS) allows attackers to inject malicious scripts into web pages viewed by other users. These scripts run with the site's privileges, enabling cookie theft, session hijacking, or UI defacement. There are three main types: Stored, Reflected, and DOM-based.
The attacker writes a dangerous note (script) and tricks the website into delivering it to other users. When the victim reads the note in their browser, the script executes as if it came from the trusted site.
1Types of XSS Attacks
XSS attacks are classified into three main types based on how the malicious payload is delivered and executed. Understanding each type helps choose the right prevention strategy.
2Stored XSS (Persistent)
The most dangerous type. Attacker submits malicious script that gets permanently stored on the server (e.g., in a comment or profile). Every user who views the page executes the script.
3Reflected XSS (Non-Persistent)
Malicious script is reflected back in the server's immediate response, usually via a crafted URL. Requires social engineering (phishing link) to trick the victim.
4DOM-based XSS
Occurs entirely on the client side. Attacker manipulates the URL or other client-side data, and vulnerable JavaScript inserts it into the DOM without proper sanitization.
5XSS Prevention Layers (Defense in Depth)
Never rely on a single layer. Use multiple overlapping protections to stop attacks even if one layer fails.
- ✓Never trust user input — always sanitize on both client and server
- ✓Use textContent or framework escaping instead of innerHTML
- ✓Implement CSP as defense-in-depth
- ✓Stored XSS affects all users; Reflected requires phishing
- ✓DOM-based XSS happens entirely client-side
- ✓Defense-in-depth is the only reliable approach