What Is XSS (Cross-Site Scripting)? Types, Attacks and Prevention
XSS lets attackers inject script into a trusted page so it runs in a victim's browser. Here are the three types, how attacks work, and how to stop them.

Cross-site scripting, or XSS, is an attack that injects malicious script into a web page so it runs in a victim's browser as if the trusted site itself had written it. OWASP, the nonprofit that maintains the industry's standard application-security guidance, describes XSS as "a type of injection, in which malicious scripts are injected into otherwise benign and trusted websites." Because the browser has no way to tell the injected code apart from the site's own code, it executes with the same trust — reaching cookies, session tokens and anything else the page has access to. XSS has been on OWASP's list of critical web risks for two decades, and it remains one of the most common vulnerabilities found in real-world applications today.
- XSS lets an attacker run their own script inside a victim's browser, in the context of a site the victim already trusts — OWASP's definition calls it an injection attack.
- There are three main types: Stored (Persistent), Reflected (Non-Persistent), and DOM-based XSS.
- OWASP notes that XSS doesn't require a
<script>tag at all — attributes likeonerrororonmouseovercan carry a working payload. - The most severe outcome is session cookie theft, which can lead directly to full account takeover.
- The core defense is context-aware output encoding combined with a strong Content Security Policy (CSP) — no single technique stops every XSS variant on its own.
What is XSS (cross-site scripting)?
Cross-site scripting happens when a web application takes input from a user — a comment, a search box, a profile field, even a URL parameter — and displays it back to other visitors without properly neutralizing it first. If that input contains script and the application renders it as live HTML instead of plain text, the browser of anyone who views that page will execute the script. OWASP's community documentation is explicit that "read-only" and seemingly static sites can still be vulnerable, because the vulnerability lives in how the page is built and displayed, not in whether the site has valuable data sitting behind a login.
The name "cross-site" is a bit of a historical artifact: the earliest XSS attacks moved data across two different sites, but today's most common forms often involve only the single vulnerable site and the victim's own browser. What hasn't changed is the underlying mechanism — an attacker's script runs with the same trust and the same access as the legitimate site's own code, because the browser has no reliable way to tell them apart once they're both sitting in the same page.
How an XSS attack actually works
Every XSS attack follows the same basic shape. First, the attacker finds a place where the application accepts input and later displays it — a search results page that echoes back the search term, a comment field, a user profile bio. Second, they craft a payload: a snippet designed to run as script once it reaches a browser, which, per OWASP, doesn't need to look like an obvious <script> tag — something as plain as <img src=x onerror="/* malicious code */"> can work just as well, since the browser still treats the onerror attribute as executable code. Third, the payload has to actually reach a victim's browser, either by tricking them into clicking a crafted link (common for reflected attacks) or by the payload sitting permanently in content other users will naturally browse to (stored attacks). Finally, the victim's browser runs the script believing it came from the trusted site, because as far as the browser can tell, it did.
The three main types of XSS
OWASP organizes XSS along two axes — where the payload is stored, and whether it executes on the server-rendered page or purely inside client-side JavaScript — but in practice, security teams and developers still talk about three familiar categories:
| Type | Where the payload lives | How it reaches the victim |
|---|---|---|
| Stored (Persistent) | Saved on the server — a database, a comment, a forum post | Runs automatically for anyone who later loads that stored content |
| Reflected (Non-Persistent) | Echoed back in the immediate server response, never saved | Victim must click a crafted link or submit a crafted form |
| DOM-based | Processed entirely in client-side JavaScript, often never touching the server at all | Victim loads a URL or page whose client-side script mishandles untrusted input |
Stored XSS, which OWASP also calls Type-II or Persistent XSS, is generally considered the most dangerous of the three, because the payload sits waiting in the application's own data and fires for every visitor who views it — no individual victim has to be tricked into clicking anything. Reflected XSS, by contrast, needs the attacker to actively deliver a crafted link to each victim, typically through phishing. OWASP also describes a variant called Blind XSS, a persistent form where the payload doesn't fire in the attacker's own view of the site at all, but later in a backend admin panel or support dashboard that a different, often more privileged, user opens — which is part of why input from low-privilege users should never be trusted even in interfaces only staff will see.
XSS vs. SQL injection: what's the difference?
XSS and SQL injection are often mentioned in the same breath because both are injection attacks rooted in the same root cause — an application trusting user input it shouldn't — but they target different layers entirely. SQL injection manipulates the database queries an application sends on the server, aiming to read, modify or delete data the attacker shouldn't have access to. XSS targets the browser of whoever views a page, aiming to run script in that victim's session rather than the server's database. A single application can be vulnerable to one, both, or neither, since they're defended against with different techniques: SQL injection is primarily stopped with parameterized queries, while XSS is primarily stopped with output encoding and a Content Security Policy.
Where XSS commonly shows up
Because the underlying flaw is simply "user input displayed without proper handling," XSS can turn up almost anywhere an application echoes something a visitor typed, uploaded, or appended to a URL. Classic injection points include search result pages that print the search term back on screen, comment sections and forum posts, user profile fields like a display name or bio, and URL query parameters that a page reads and renders directly — a common pattern on error pages that display "No results found for: [your search]" without encoding that bracketed text first. Less obvious injection points matter too: an admin dashboard that displays raw HTTP request headers, support-ticket fields, or file names from an upload feature can all carry a payload into a context — often a more privileged one — that the original developer never thought to treat as untrusted.
OWASP's current categorization groups all of this along two axes rather than treating Stored, Reflected and DOM-based XSS as three fully separate things: one axis is where the payload is stored (Stored vs. Reflected), and the other is where it executes (Server vs. Client). DOM-based XSS falls specifically under the Client side of that grid, and OWASP notes the categories genuinely overlap — a single flaw can qualify as both Stored and DOM-based at once, for instance, if a stored value is later read and unsafely inserted into the page by client-side JavaScript rather than by server-rendered HTML.
Impact and risks of a successful XSS attack
OWASP's community documentation lists a consistent set of consequences regardless of which XSS variant was used to get there, including session cookie theft leading to account takeover, disclosure of files the victim's browser had access to, installation of trojan-style follow-on payloads, forced redirects to attacker-controlled sites, and altering displayed content — OWASP's own examples include tampering with something as consequential as a posted press release or displayed medical dosage information. Session cookie theft is generally treated as the most severe single outcome, since a stolen session token can let an attacker impersonate the victim entirely without ever needing their password.
How to prevent XSS
OWASP's Cross Site Scripting Prevention Cheat Sheet is explicit that no single technique eliminates XSS on its own — effective defense combines several layers:
- Context-aware output encoding. Any user-supplied data rendered back into a page must be encoded for the specific context it lands in — HTML body, an HTML attribute, a URL, or inline JavaScript each require different encoding rules.
- Content Security Policy (CSP). MDN describes CSP as an HTTP response header that tells the browser which sources of script, style and other resources a page is allowed to load from, blocking inline
<script>blocks, inline event handlers likeonmouseover, and unsafe APIs likeeval()by default once ascript-srcdirective is set. MDN is explicit that CSP is a second line of defense, not a replacement for proper input handling — sites should use both. - Sanitize any HTML you must allow. If an application genuinely needs to accept some HTML formatting from users — a rich-text comment box, for example — OWASP's cheat sheet recommends a dedicated sanitization library such as DOMPurify rather than attempting to filter dangerous markup by hand.
- Validate Content-Type on API responses. OWASP's guidance also flags that JSON API responses should be served with a
Content-Type: application/jsonheader rather thantext/html, since a browser that misinterprets a JSON response as HTML can end up executing content inside it.
MDN's recommended, stricter form of CSP uses a per-response nonce or a content hash rather than a plain allowlist of trusted domains, specifically because allowlists are easy to get subtly wrong and can end up permitting a domain an attacker can also use. A policy like script-src 'nonce-{RANDOM}'; object-src 'none'; base-uri 'none';, with a freshly generated random value on every response and the matching value placed on every legitimate <script nonce="..."> tag, blocks any injected inline script from running even if it does make it into the page.
How to check if a site is vulnerable
For developers and security teams, the starting point is the same OWASP guidance covered above: review every place user input is rendered back into a page and confirm it's passed through context-appropriate encoding, and check whether a Content Security Policy header is set at all. For end users, there's no reliable way to visually detect that a page has an XSS flaw before it's exploited, since a successful attack is designed to look like normal page behavior — which is exactly why the responsibility for preventing XSS sits with the people building and maintaining the application, not the people browsing it.
What to do next
If you're building or maintaining a web application, treat OWASP's Cross Site Scripting Prevention Cheat Sheet as the baseline reference, since it's updated as new bypass techniques and framework-specific guidance emerge. If you're evaluating a vendor or a product, ask directly whether they run regular security testing for injection flaws, including XSS, and whether they ship a Content Security Policy — a site that's never heard of CSP is a weaker bet than one that actively tells browsers what it will and won't load. And because XSS and other injection flaws are rarely found in isolation, the same review that catches one typically turns up the kind of other vulnerability classes worth checking for across an application at the same time.
Frequently asked questions
What is XSS (cross-site scripting)?
XSS is an attack that injects malicious script into a trusted web page so it runs in a victim's browser as if the site itself had written it, letting the attacker access cookies, session tokens and other data the page can reach.
What are the three types of XSS?
Stored (Persistent) XSS, where the payload is saved on the server and runs for anyone who later views it; Reflected (Non-Persistent) XSS, where the payload is echoed back in a single response after a victim clicks a crafted link; and DOM-based XSS, which executes entirely in client-side JavaScript.
What is the difference between XSS and SQL injection?
Both are injection attacks caused by trusting user input, but SQL injection manipulates a server's database queries, while XSS runs malicious script in a victim's browser. They require different defenses: parameterized queries for SQL injection, and output encoding plus a Content Security Policy for XSS.
What is the worst-case impact of an XSS attack?
Session cookie theft is generally considered the most severe outcome, since a stolen session token can let an attacker impersonate the victim and take over their account without needing a password.
How do you prevent XSS?
OWASP recommends combining context-aware output encoding of all user-supplied data, a strong Content Security Policy to block inline scripts and unsafe APIs, sanitizing any HTML you must allow with a library like DOMPurify, and serving API responses with the correct Content-Type header.
Sources
- OWASP: Cross Site Scripting (XSS)community.owasp.org
- OWASP Cheat Sheet Series: Cross Site Scripting Preventioncheatsheetseries.owasp.org
- MDN Web Docs: Content Security Policy (CSP)developer.mozilla.org
- OWASP Foundationowasp.org
Sana Qureshi runs the security and privacy desk. She reports on actively exploited vulnerabilities, vendor patches and data breaches, and covers the password managers, VPNs and authentication tools readers use to protect themselves. Her alerts cite vendor advisories, CISA and the CVE record directly.