Cross-Site Scripting (XSS) is a web security vulnerability that allows an attacker to inject malicious scripts – usually JavaScript – into web pages that are then executed in the browsers of other users. Because the malicious code runs in the victim’s browser within the context of a trusted website, it can access that site’s cookies, session tokens, and page content, and act as if it were the legitimate site. XSS is a client-side attack and a long-standing, prevalent member of the OWASP Top 10.
XSS arises when an application takes untrusted input (for example, from a URL parameter, form field, or stored data) and includes it in a web page without properly validating or encoding it. The browser cannot distinguish the injected script from legitimate page code, so it executes the attacker’s script. There are three common types. Reflected XSS occurs when malicious input is immediately echoed back in a response – for instance, in a search results page or error message – so an attacker crafts a malicious link that, when clicked, executes the script. Stored (persistent) XSS occurs when the malicious script is saved on the server (in a comment, profile field, or message) and served to everyone who views that content, making it especially dangerous because it can affect many users automatically. DOM-based XSS occurs entirely in the browser, when client-side JavaScript manipulates the page using attacker-controllable data.
The impact of XSS can be severe: stealing session cookies to hijack accounts, capturing keystrokes and credentials, redirecting users to malicious sites, defacing pages, performing actions on behalf of the victim, and delivering further attacks. Because it exploits the trust between a user and a website, XSS can compromise users at scale, particularly in the stored variant.
Preventing XSS centers on treating all user-supplied data as untrusted: contextual output encoding/escaping so that data is rendered as text rather than executable code, input validation, using frameworks that auto-escape output, and deploying a Content Security Policy (CSP) to restrict which scripts a page may run. Modern APIs that return data to browsers must also ensure that data cannot be interpreted as executable script when rendered.