Cross-Site Scripting (XSS) is a web security vulnerability that allows attackers to inject malicious scripts, typically JavaScript, into web pages viewed by other users. When a web application fails to properly validate or sanitize user input before including it in its output, an attacker can craft input that executes arbitrary code in the victim's browser. XSS consistently ranks among the most common and dangerous web application security risks, appearing regularly in the OWASP Top 10.
There are three primary types of XSS attacks, each with different attack vectors and persistence levels:
- Stored XSS (Persistent) – The malicious script is permanently saved on the target server (e.g., in a database, comment field, or forum post) and executes whenever a user views the affected page.
- Reflected XSS (Non-Persistent) – The malicious script is embedded in a URL or request parameter and reflected back in the server's response, typically requiring the victim to click a crafted link.
- DOM-based XSS – The vulnerability exists in client-side JavaScript that processes untrusted data and modifies the DOM without proper sanitization, never involving the server.
The consequences of XSS attacks can be severe. Attackers can steal session cookies and authentication tokens, hijack user accounts, redirect users to malicious websites, deface web pages, capture keystrokes, or perform actions on behalf of the victim. In enterprise environments, a single XSS vulnerability can lead to data breaches and compliance violations.
Preventing XSS requires layered defenses throughout the development process. The main mitigation strategies include output encoding (escaping HTML, JavaScript, and URL contexts), input validation and sanitization, Content Security Policy (CSP) headers, using modern frameworks that auto-escape output by default (like React or Angular), and setting the HttpOnly flag on sensitive cookies. Automated security scanning and regular code reviews help catch XSS issues before they reach production.