Security operations

Cross-Site Scripting (XSS): What It Is, the 3 Types, and How to Stop It

Cross-site scripting turns your own website into the attacker's delivery system. Here are the three types, what an injected script can actually do, and the defenses OWASP recommends.

Cysoro Security TeamPublished · 9 min read
<div> Great post! </div><script> steal(cookie) </script><div> Thanks for sharing </div>⚠ injected script runs herebrowser trusts it — it came fromyour own site SECURITY OPERATIONS Cross-sitescripting Your site delivers the attack.
Quick answer

Cross-site scripting (XSS) is a web vulnerability in which an attacker injects malicious script, usually JavaScript, into pages that other users view. The script runs in the victim's browser with the trust of the vulnerable site, so it can steal session cookies, impersonate the user, deface pages, or redirect visitors. It is classified as CWE-79 and falls under injection in the OWASP Top 10.

Key takeaways

  • XSS happens when untrusted data is rendered as code instead of text — the fix is context-aware output encoding, not input filtering alone.
  • Stored XSS is the most dangerous type because one injection hits every viewer; DOM-based XSS is the hardest to spot because it never touches the server.
  • A Content Security Policy and HttpOnly cookies limit the damage, but they are second layers — encoding and safe sinks come first.

Your website does not have to be hacked for an attacker to run code in your visitors' browsers. With cross-site scripting, your own pages do the delivery — and the browser cannot tell your code from the attacker's.

What is cross-site scripting?

Cross-site scripting (XSS) is a web vulnerability in which an attacker injects malicious script, usually JavaScript, into pages that other users view. The script then runs in the victim's browser with the privileges of the vulnerable site.

OWASP puts it plainly: XSS attacks are a type of injection in which malicious scripts are injected into otherwise benign and trusted websites. The name is a historical misnomer — the original attacks stole data across sites, but today the term covers the injection of basically any content, according to the OWASP XSS Prevention Cheat Sheet.

The core mistake is simple: the application puts untrusted data into a page in a way that lets the browser treat it as code. A comment that should appear as plain text instead runs as JavaScript. Untrusted data is anything your application did not create itself — form input, URL parameters, stored user content, and responses from other services.

XSS is classified as CWE-79: Improper Neutralization of Input During Web Page Generation. In the OWASP Top 10, it sits under injection: the 2017 list gave XSS its own category, A7, and the 2025 list folds it into A03 Injection.

How does an XSS attack work?

An XSS attack has three parts: a place where attacker input enters your application, a place where that input is rendered without proper encoding, and a victim whose browser runs the result as your site's own code.

How cross-site scripting works1Attacker injectsscript hidden in acomment or link2Site serves itstored in the page,or bounced back3Browser trusts itruns as your site,not the attacker4Attacker winssession, dataor redirectThe browser cannot tell your code from injected code — that is the whole vulnerability.The fix must happen where the data is rendered, not where the user types.
The XSS chain: injection, delivery by your own site, execution under your site's trust. Illustration by Cysoro.

Take a comment box. An attacker submits a comment containing a script tag. If the site stores it and later prints it into the page without encoding, every visitor who loads that comment runs the script. The browser has no reason to refuse: the script came from your domain, over your HTTPS connection.

The injected script can do anything the victim can do on your site. It can read the page, send requests as the victim, change what the victim sees, and — unless cookies are protected — steal the session cookie and hand it to the attacker.

What are the three types of XSS?

The three types are stored, reflected and DOM-based XSS. They differ in where the payload lives and how it reaches the victim, not in what the script can do once it runs.

TypeWhere the payload livesWho it hitsHow it is deliveredRisk
Stored (persistent)Saved on the server — database, comment, profileEvery viewer of the pageVictim just visits the pageHighest — inject once, hit many
Reflected (non-persistent)In the request — URL parameter or form fieldOne victim per crafted linkVictim clicks a malicious linkHigh, but needs social engineering
DOM-basedIn the browser — URL fragment or page dataWhoever loads the page with the inputPage script writes input into a sinkHigh — invisible to the server
Blind XSSStored, but fires in a different appAdmins or support staffPayload runs in an admin panelHigh — targets privileged users

Stored XSS (persistent XSS)

Stored XSS is the most dangerous type. The malicious script is saved on the server — in a comment, forum post, product review, user profile or message — and served to every user who views that content. The attacker injects once and the payload fires for everyone.

A stored XSS flaw in a high-traffic field is effectively a worm vector: it can hit thousands of authenticated users from a single injection. Admin panels are a favorite target, because the person who views the payload often has the highest privileges.

Reflected XSS (non-persistent XSS)

Reflected XSS is non-persistent. The script is part of the request, typically in a URL parameter, and the server reflects it straight back in the response — an error message, a search-results page, anything that echoes input.

The victim has to click a crafted link or submit a crafted form, so reflected XSS usually arrives wrapped in spear phishing or a malicious ad. It hits one victim at a time, but it is the easiest type to find and the most common in bug-bounty reports.

DOM-based XSS

DOM-based XSS never involves the server reflecting the payload. It lives entirely in client-side JavaScript: the page's own script reads attacker-controllable input — the URL fragment after #, document.location, window.name — and writes it into the page through a dangerous sink such as innerHTML or document.write.

That makes it the hardest type to detect. Stored and reflected XSS show up in request and response logs; DOM-based XSS may leave no server-side trace at all. It grows more relevant as applications push more logic into the browser, and it was first described by Amit Klein in 2005.

Blind XSS

Blind XSS is a subtype of stored XSS. The payload is stored by the server but executes in a completely different application or admin interface that the attacker cannot directly observe — for example, a support ticket that only staff can read. The attacker learns it worked when the payload phones home.

What can an attacker do with XSS?

An injected script runs with the victim's session on your site, so its power is bounded only by what the victim can do there. The most common goals are session theft, impersonation and redirection.

  • Session hijacking: steal the session cookie and log in as the victim — unless the cookie is marked HttpOnly.
  • Account takeover: change the victim's email or password, or trigger actions such as transfers and purchases.
  • Credential and keystroke theft: add a fake login form or log keystrokes on the real one.
  • Defacement and misinformation: rewrite page content for every visitor who loads it.
  • Phishing from your domain: redirect visitors to a look-alike login page — the URL in the address bar still starts with your site until the redirect.
  • Malware delivery and worming: stored XSS can spread from user to user, as the Samy worm did on MySpace in 2005, adding over a million friends in under a day.

The Samy worm is the classic demonstration: a single stored XSS payload in a MySpace profile automatically added its author as a friend and copied itself into every visitor's profile. No one had to click anything suspicious — they only had to view a profile.

XSS vs SQL injection vs CSRF: what's the difference?

These three flaws are often confused because they all involve untrusted input, but they attack different layers. Knowing which one you are looking at decides the fix.

AttackTargetWhat the attacker injectsPrimary fix
XSSThe victim's browserScript into a web pageContext-aware output encoding
SQL injectionYour databaseSQL into a queryParameterized queries
CSRFThe victim's browser sessionA forged request, no codeAnti-CSRF tokens + SameSite cookies

XSS runs code in the browser. SQL injection runs code in the database. CSRF runs no code at all — it tricks the browser into sending a request the user never intended. A site can be vulnerable to one, two or all three at once.

How do you prevent cross-site scripting?

OWASP's prevention guidance is built on one principle: coverage. An application that protects 99 places where untrusted data is rendered and misses one is still vulnerable. The defenses below work as a stack, in this order.

Five layers that stop XSS1Context-aware output encodingencode every value for where it lands: HTML, attribute, JS, CSS or URL2Safe sinks, not dangerous onestextContent and setAttribute instead of innerHTML and document.write3Sanitize user HTMLDOMPurify for rich text; never write your own sanitizer4Content Security Policysecond layer: block inline scripts, allow only trusted sources5Harden cookiesHttpOnly, Secure and SameSite so a stolen script cannot steal the session
OWASP's XSS defense stack — encoding first, CSP and cookie flags as second layers. Illustration by Cysoro.

1. Encode output for its context

Output encoding is the primary defense. Encode every untrusted value at the moment it is inserted into a response, choosing the encoding for where the value lands — HTML body, HTML attribute, JavaScript, CSS or URL — because browsers parse each context differently.

Most modern frameworks escape by default, which is why OWASP recommends letting the framework do it for every value, trusted or not. The danger is the escape hatches: React's dangerouslySetInnerHTML, Angular's bypassSecurityTrustAs* functions and Lit's unsafeHTML all bypass that protection.

2. Use safe sinks

Prefer APIs that treat input as text. Assigning to textContent creates a text node without parsing HTML; setAttribute with a fixed attribute name does not execute anything. Refactor away from innerHTML, document.write, eval() and setTimeout with a string.

3. Sanitize user-authored HTML

When users need to author formatted HTML — a rich-text editor, for example — encoding would break the feature. Use a maintained sanitizer instead. OWASP recommends DOMPurify, and warns to keep it patched, because browsers change and bypasses are discovered regularly.

4. Add a Content Security Policy

A Content Security Policy (CSP) is an extra layer, not the primary defense. A restrictive policy such as default-src 'self'; script-src 'self' stops the browser running inline scripts and scripts from untrusted sources, which limits what an injected payload can do.

Roll it out in report-only mode first, then enforce it. The OWASP HTTP Headers Cheat Sheet recommends CSP over the legacy X-XSS-Protection header, which should be set to 0 or left unset. Check your own headers with our free security headers checker.

5. Harden session cookies

Mark session cookies HttpOnly so JavaScript cannot read them, Secure so they only travel over HTTPS, and SameSite=Lax or Strict to limit cross-site sending. HttpOnly does not stop XSS — the injected script can still act as the user — but it does stop the simplest session theft.

Common XSS mistakes to avoid

Most XSS flaws survive because a team fixed the obvious cases and missed the subtle ones. These are the mistakes OWASP calls out most often.

  • Filtering input instead of encoding output. Blocklists of bad words are bypassed constantly; encode at render time instead.
  • Encoding for the wrong context. HTML-encoding a value inside a JavaScript string or a URL does not protect it — each context needs its own encoding.
  • Trusting data because it came from your own database. Stored XSS is exactly that: data your server saved and later rendered.
  • Using innerHTML with user data. One call undoes every encoding rule above it.
  • Treating CSP as the fix. A policy with unsafe-inline or a broad allowlist gives a false sense of security.
  • Forgetting the URL fragment. DOM-based XSS often hides after the #, where server logs never look.

How do you find and test for XSS?

Test in a staging environment you own. Automated scanners catch reflected and stored XSS in common fields, but DOM-based XSS usually needs manual code review of client-side sinks and sources.

  1. Map every input: form fields, URL parameters, headers, file uploads, and data from third-party APIs.
  2. Submit test strings and watch whether they are reflected or stored unencoded — use a harmless marker, never a real payload against a live site.
  3. Review client-side code for innerHTML, document.write, eval and unvalidated URL handling.
  4. Check headers and cookies with a headers scan, and confirm CSP is enforced rather than report-only.
  5. Fix, retest, and add regression tests so the same sink cannot come back in a later release.

For a wider starting point, our small business cybersecurity checklist covers web hardening alongside backups, updates and device security.

The bottom line

Cross-site scripting is not a flaw in the browser — it is a flaw in how your application renders data. Encode every untrusted value for its context, use safe sinks, sanitize rich text with a maintained library, and layer CSP and HttpOnly cookies on top.

Start with the highest-traffic pages your users can write to: comments, profiles, search and support tickets. Then check your site's headers in seconds with the free security headers checker.

Frequently asked questions

What is cross-site scripting in simple terms?

Cross-site scripting is an attack where someone smuggles their own JavaScript into a page on your website, and the browser of every visitor runs it as if your site wrote it. The attacker does not need your server password — they abuse the trust browsers place in your domain.

What are the three types of XSS?

Stored XSS saves the payload on the server, for example in a comment, and it runs for every viewer. Reflected XSS bounces the payload straight back in a response, usually via a crafted link. DOM-based XSS runs entirely in the browser when page JavaScript writes attacker input into a dangerous sink such as innerHTML.

Is XSS still a problem in 2026?

Yes. Modern frameworks escape output by default, which has reduced basic cases, but escape hatches, rich-text editors, single-page apps and third-party scripts keep XSS alive. OWASP still lists injection, which includes XSS, in its Top 10, and XSS is classified as CWE-79.

What can an attacker do with XSS?

An injected script runs with the victim's session on your site, so it can steal session cookies, read page content, capture keystrokes, change what the victim sees, submit forms as the victim, and redirect them to a phishing page. Stored XSS can spread like a worm across users.

How do you prevent cross-site scripting?

Encode untrusted data for the exact context where it appears, use safe sinks such as textContent instead of innerHTML, sanitize user-authored HTML with a maintained library such as DOMPurify, and add a Content Security Policy as a second layer. Mark session cookies HttpOnly, Secure and SameSite.

Does a Content Security Policy stop XSS?

No, not on its own. A Content Security Policy limits which scripts the browser will run, which reduces the impact of an injection, but OWASP treats it as an additional layer. If the policy allows inline scripts or the attacker can inject into an allowed source, XSS still works. Encoding is the primary defense.

What is the difference between XSS and CSRF?

XSS injects the attacker's script into your site so it runs in the victim's browser. CSRF tricks the victim's browser into sending a request to your site that the victim did not intend. XSS is about code running on your pages; CSRF is about forged requests. They are different flaws with different fixes.

How do you test for XSS?

Use automated scanners and manual testing in a staging environment you own: submit test strings into every input, URL parameter and header, and check whether they are reflected or stored unencoded. Also review client-side code for dangerous sinks such as innerHTML and document.write. Never test against a site you do not own or have permission to test.

Sources

  1. OWASP — Cross Site Scripting Prevention Cheat Sheet
  2. OWASP — HTTP Headers Cheat Sheet
  3. OWASP Top Ten 2017 — A7:2017 Cross-Site Scripting (XSS)
  4. CyberDefenders — What Is Cross-Site Scripting (XSS)? Types and Defenses
  5. MITRE CWE — CWE-79: Improper Neutralization of Input During Web Page Generation
Written & fact-checked byCysoro Security Team

The engineers and analysts who build Cysoro's domain scanner, email-authentication checks and free security tools. We test what we write about every day — SPF, DKIM, DMARC, certificates, look-alike domains and phishing — and check each guide against the relevant standards, government guidance and vendor documentation.

  • Email authentication
  • Phishing & BEC
  • Domain & DNS security
  • Small-business security

Checked against the OWASP XSS Prevention Cheat Sheet, the OWASP HTTP Headers Cheat Sheet and CWE-79.

How we write and fact-check →

Free tools for this topic

No account needed.

See where your domain stands

Free for up to 3 domains. No card, no installs.

Start free