What is XSS?
XSS (Cross-Site Scripting) is a web security vulnerability where an attacker injects malicious scripts into web pages viewed by other users, enabling theft of session tokens, cookies, personal data, or the ability to perform actions on behalf of the victim.
How Does XSS Work?
XSS attacks occur when a web application includes untrusted data in its output without proper validation or escaping. There are three main types: Stored XSS, where the malicious script is permanently saved on the target server (such as in a comment or forum post) and served to every user who views that page; Reflected XSS, where the script is embedded in a URL or form submission and reflected back in the server's response; and DOM-based XSS, where the vulnerability exists in client-side JavaScript that processes untrusted data.
Preventing XSS requires a defense-in-depth approach. The most important measure is output encoding — ensuring all user-supplied data is properly escaped for the context where it appears (HTML, JavaScript, CSS, or URL). Content Security Policy (CSP) headers provide a second line of defense by restricting which scripts the browser is allowed to execute. Modern front-end frameworks like React and Vue automatically escape output by default, significantly reducing XSS risk. Additional measures include input validation, HTTPOnly cookie flags (preventing JavaScript from accessing session cookies), and using trusted sanitization libraries for any HTML that must be rendered.