← Glossary

What Is Cross-Site Scripting (XSS)?

Cross-site scripting (XSS) is a web vulnerability in which a site runs attacker-supplied script as if it were its own code, because untrusted input was inserted into a page or a script-executing API without being neutralised first.

Updated:

Cross-site scripting, usually shortened to XSS, is a web vulnerability in which a site ends up running script that an attacker supplied, as though that script were part of the site's own code. The browser cannot tell the difference. The injected code runs under the site's origin, so it can read the page, reach storage and any cookies that scripts are allowed to see, and send requests that carry the victim's logged-in state. Despite the name, nothing has to cross between sites in the network sense. The defining feature is that untrusted input is interpreted as code inside a trusted page.

How Untrusted Data Reaches Script Execution

Browsers parse HTML and JavaScript according to context. The same characters mean different things inside an element's text, inside a quoted attribute, inside a script block or inside a URL. When a page inserts raw input into one of these contexts, the input can close the current context and open a new one. For example, a search query intended to appear as text can become an HTML element if the page inserts it as raw markup. That is a parsing error in the application's design, not a special permission the visitor granted.

The dangerous insertion points are called sinks. HTML sinks interpret a string as markup: innerHTML, outerHTML, insertAdjacentHTML() and document.write(). Code-execution sinks run a string as JavaScript: eval() and the string forms of setTimeout() and setInterval(). Server-side templates become sinks when they concatenate strings into a response. A value that is harmless in one sink may be executable in another, which is why the right fix always depends on where the data lands.

Sources of untrusted data are wider than text a user typed a moment ago. URL fragments, messages received through postMessage, responses from third-party APIs, uploaded file names, and fields an administrator edited months earlier all count. Trust is about where the data came from, not about how harmless it looks.

Reflected, Stored and DOM-Based XSS

The familiar labels describe persistence or the place where unsafe rendering happens; they can overlap.

Reflected XSS occurs when the server includes request data directly in its response. The input arrives in a request, perhaps through a link or form submission, and returns in the generated page. It need not remain in the site's database; exploitation depends on causing a victim to make the affected request.

Stored XSS occurs when the payload is written to a database or file and served later to other users. A comment, a profile name or a support ticket can carry it. Visitors who receive the affected content may encounter the script during an ordinary visit. Persistence can increase its reach, although severity also depends on the affected users, privileges and available defenses.

DOM-based XSS happens entirely in the browser. Client-side JavaScript reads a source such as location.hash or a URL parameter and writes it into a sink such as innerHTML. The server response can be perfectly clean, so server-side filters never see the payload and server logs may not record it.

Real applications mix these routes. A single-page application might store a payload through an API and later render it client-side, which is both stored and DOM-based. The categories tell a reviewer where to look. They do not change the remedy, which is correct handling at the sink.

Encoding, Sanitization and Browser Defenses

Output encoding is the primary defense. Before inserting data into a page, the application converts characters that carry meaning in the target context into inert equivalents, so a less-than sign becomes the entity < in HTML text. Encoding is context-specific. HTML entity encoding protects element content and quoted attributes, but not an unquoted attribute, an event handler, a script block, a CSS value or a URL. OWASP's prevention guidance treats each of these as a separate rule and warns that untrusted data inside event handlers, inline scripts or style sheets stays unsafe even when encoded. Frameworks commonly escape text by default, but escape hatches and hand-built markup can remove that protection.

Sanitization is for the narrower case where users are allowed to submit HTML, such as a rich-text editor. A sanitizer parses the markup and removes dangerous constructs, so an image element with an onerror attribute is returned as a plain image element. Use a maintained sanitizer suitable for the accepted markup. Later modifications can undo its protection, so the complete rendering path still needs review.

Browser-level controls add depth. A Content Security Policy (CSP) built on nonces or hashes tells the browser which scripts may run, so an injected inline script is refused even after it reaches the page. Trusted Types, enforced through CSP, makes passing a plain string to a dangerous sink throw an error, which forces every sink write through a reviewed policy. Safer DOM APIs help too: textContent treats input as text. Attribute setters require a known safe attribute; fixing the name alone does not make an event handler or an unsafe URL safe.

XSS Compared With CSRF and Ordinary Script Loading

Cross-site request forgery (CSRF) tricks a browser into sending a request the user did not intend, relying on cookies being attached automatically. CSRF does not execute code on the target site and cannot read its responses. XSS can do both. Injected scripts may also defeat CSRF protections by reading tokens exposed to the page and making requests from the trusted origin.

XSS is also not the same as a page loading its own third-party scripts. A site that embeds an analytics or chat widget has chosen to trust that code, and a compromise of the supplier is a supply-chain problem rather than XSS. The term applies when input the site never intended to execute is executed because of how the site handled it. Running scripts of your own choosing in a browser you control is a different subject entirely.

Where Each Defense Stops

No single control is complete. Encoding protects only the contexts it was applied to, and one forgotten template variable reopens the hole. Sanitizers can be bypassed by markup their parser reads differently from the browser. CSP does not repair unsafe rendering. Broad script permissions can undermine it, and even a trusted script needs to handle untrusted values safely.

Cookie attributes shrink the blast radius rather than stop the attack. An HttpOnly session cookie cannot be read by injected script, but the script may still perform actions available to the page without seeing the cookie value. Server-side permissions and fresh authentication requirements can limit what succeeds. Web application firewalls match known payload patterns and can be evaded with encoding tricks. The durable approach is to treat output handling as part of the application's design: encode by default, sanitize only where HTML is genuinely required, and deploy a strict CSP as a safety net for the mistakes that will still happen.

Frequently asked questions

Is XSS the same as CSRF?

No. CSRF induces an unwanted request using the victim's browser credentials; it does not itself execute code in the target site's origin. XSS runs script within that origin and can often read page data or tokens used by CSRF defenses.

Does HttpOnly prevent all XSS damage?

No. HttpOnly prevents page scripts from reading the protected cookie value. An injected script may still submit authenticated requests or read visible information. Server-side authorization and reauthentication can restrict damage, but the unsafe rendering must still be fixed.

Can CSP replace output encoding?

No. A strict CSP with nonces or hashes can stop an injected script from executing, but the injection itself remains, and weak policies or allowed inline code leave it exploitable. Both MDN and OWASP treat CSP as an additional layer behind encoding and sanitization.

Why is DOM-based XSS harder to catch on the server?

Because the payload may never reach the server. Client-side code reads it from a URL fragment or another browser-side source and writes it to a sink directly. Server logs and server-side filters see a normal request, so detection has to happen in the front-end code or through browser testing.

Does a modern framework make XSS impossible?

No. Frameworks such as React or Angular escape output by default, which removes many classic cases. Exposures remain wherever developers bypass that protection with raw HTML insertion, trust data in event handlers or URLs, or render user-supplied HTML without a maintained sanitizer.