Question

What is cross-site scripting (XSS)?

Vault Verified
Curated Intelligence
Definitive Source
Answer

An attack where attacker-controlled content is executed as JavaScript in another user's browser, in the context of your site — which means it runs with that user's session, cookies and permissions.

Why it matters more than it sounds. The injected script can read the DOM, steal session tokens, make authenticated requests as the user, modify the page, log keystrokes, and redirect. The browser has no way to distinguish it from your own code, because as far as it is concerned it is your code.

The three types:

Stored XSS. The payload is saved on the server — in a comment, a profile field, a message — and served to everyone who views it. The most serious, because it needs no interaction beyond viewing a page.

Reflected XSS. The payload is in the request, usually a URL parameter, and echoed back in the response. Requires tricking a user into following a link.

DOM-based XSS. Never reaches the server at all — client-side JavaScript reads something attacker-controlled, such as the URL fragment, and writes it into the page unsafely.

The fix, stated correctly: context-aware output encoding. Escape data when you output it, using encoding appropriate to where it lands. HTML body, HTML attribute, JavaScript string, URL parameter and CSS each require different escaping — applying HTML escaping to a value inserted into a script block does not protect you.

What actually prevents it in practice:

Use a framework that escapes by default, and treat every escape-hatch — dangerouslySetInnerHTML, v-html, innerHTML — as requiring justification.

Prefer textContent over innerHTML when inserting text.

Sanitise HTML with a maintained library where users genuinely need rich text. Do not write your own sanitiser.

Content Security Policy, which limits what can execute even if injection occurs — a genuine second line of defence.

HttpOnly cookies, so session tokens cannot be read by script.

Validate input as a secondary control, since the primary defence is at output.

Mutation XSS and sanitiser bypasses exist, which is why CSP matters.

Related Questions