How it works
XSS happens when text from a user, such as a comment, a profile name or a URL parameter, is placed into a page as HTML instead of as plain text. The browser cannot tell the attacker's script from the site's own, so it runs with the site's full access: it can read what the page shows, send requests as the victim, change the page or redirect them. Stored XSS is saved on the server and hits everyone who views it, reflected XSS bounces off a crafted link, and DOM-based XSS happens entirely in front-end JavaScript.
The core defence is output encoding: show user text as text. React, Vue, Angular and Svelte do this by default, so most of the risk comes from escape hatches such as dangerouslySetInnerHTML in React, v-html in Vue or innerHTML in plain JavaScript. When real HTML must be shown, for example from a rich text editor or rendered Markdown, it is cleaned first with a sanitiser such as DOMPurify.
A Content Security Policy then limits which scripts may run at all, as a second line of defence, and HttpOnly cookies stop scripts from reading the session cookie, although an injected script can still act inside the page. XSS sits in the injection category of the OWASP Top 10.
Cross-site scripting (XSS) vs the alternatives
Related terms
More in Security
Common attacks