What Is XSS (Cross-Site Scripting)? Types and Prevention
We explain how XSS works, its reflected, stored and DOM-based types, how it differs from CSRF, and how output encoding, CSP and cookie settings help.

Short answer: XSS (cross-site scripting) is an injection vulnerability in which a malicious script that an attacker plants on a website runs in other users' browsers as if it were the site's own code. It arises when an application puts user-supplied data into a page without neutralizing it, and it comes in three types: reflected, stored and DOM-based. Attackers can use it to hijack sessions, send requests on the user's behalf or alter the page. The primary defense is encoding output for its context; Content Security Policy (CSP) and HttpOnly cookies form a second line of defense.
What is XSS?
OWASP defines cross-site scripting as a type of injection in which malicious scripts are injected into otherwise benign and trusted websites. In the weakness described by MITRE's CWE-79 entry, the software does not neutralize, or incorrectly neutralizes, user-controllable input before placing it in a web page that is served to other users.
Data enters the application from an untrusted source, most often a web request, and ends up in content sent to users without being validated. The browser has no way of knowing that a script arriving this way should not be trusted, so it runs it; according to MDN, the code can then do anything the site's own code can do. XSS belongs to the same family as SQL injection: there, input leaks into a database query; here, it leaks into the page the browser interprets.
Types of XSS: reflected, stored and DOM-based
- Reflected XSS: The script is reflected back in a server response such as an error message or a search result. The victim is tricked into clicking a link in an email or on another website; according to CWE, URLs built this way are at the core of many phishing schemes.
- Stored XSS: The script is stored permanently somewhere such as a database, a forum or a comment field, and the victim receives it when requesting the stored information. OWASP's testing guide calls this the most dangerous type: no malicious link is needed, and if an administrator opens the page, the attack runs in the administrator's browser.
- DOM-based XSS: According to OWASP, the attack works because the DOM in the victim's browser has been modified, while the server's response stays the same. If the attack input sits after the # in the URL, it never reaches the server at all.
What can an XSS attack do?
According to OWASP, the most severe XSS attacks expose the user's session cookie, letting the attacker hijack the session and take over the account. Other consequences include:
- Acting as the user: According to MDN, the code can make HTTP requests with the user's credentials and impersonate the user; the site's APIs treat those calls as if they came from the user.
- Fake forms: According to CWE, XSS can be used in phishing attacks that emulate a trusted site and trick the victim into entering a password.
- Altering the page: The script can rewrite the page's content, redirect the user to another site or install Trojan horse malware.
How common is XSS?
CWE-79 ranks first in the 2025 CWE Top 25, which the CWE program announced on December 11, 2025. According to the announcement, the list draws on 39,080 CVE Records for vulnerabilities published between June 1, 2024, and June 1, 2025. CSRF (CWE-352) is third on the same list. OWASP Top 10:2025 places XSS in the A05:2025 Injection category and describes it as a high-frequency weakness with more than 30,000 CVEs. And according to the Secure by Design Alert that CISA and the FBI published in September 2024, XSS vulnerabilities are preventable and should not be present in software products at all.
How to prevent XSS
According to OWASP's XSS prevention cheat sheet, no single technique will solve XSS; it takes the right combination of defenses:
- Context-aware output encoding: Data is encoded for the context it lands in (HTML body, attribute, JavaScript, CSS or URL) before it goes into the page. According to CWE, proper output encoding, escaping and quoting is the most effective way to prevent XSS. OWASP advises against placing variables into unsafe functions such as eval at all, because encoding does not fully protect them.
- Keeping the framework's auto-escaping intact: Modern frameworks reduce XSS bugs through templating and auto-escaping. Vulnerabilities can still slip in through escape hatches that switch this protection off: React's dangerouslySetInnerHTML, Angular's bypassSecurityTrust functions, template injection and outdated plugins. React's documentation warns that unless the markup comes from a completely trusted source, it is trivial to introduce an XSS vulnerability this way.
- HTML sanitization: When users author HTML, output encoding prevents XSS but also breaks the intended formatting, so OWASP recommends a sanitization library such as DOMPurify for these cases. Modifying content after it has been sanitized can easily void the protection.
- Safe APIs and input validation: According to OWASP, the strongest defense in code that runs in the browser is using safe JavaScript APIs, such as textContent instead of innerHTML. CISA and the FBI call for validating input for both structure and meaning, while CWE notes that allowlist-based input validation provides only some defense in depth.
Content Security Policy (CSP) as a second line of defense
According to the W3C's CSP Level 3 draft, CSP is a mechanism that lets developers control which resources a page can fetch or execute, and MDN says its main use is defending against XSS. The recommended approach is a nonce- or hash-based strict CSP: the server generates a new, unpredictable nonce for every HTTP response and writes it into both the policy and the script tags it intends to include; if the values do not match, the browser does not load the script. The 'unsafe-inline' keyword defeats much of the purpose of having a CSP. The example below extends MDN's nonce-based policy with two directives, one that blocks clickjacking and one that requests violation reports (split across lines for readability):
Content-Security-Policy:
script-src 'nonce-{RANDOM}';
object-src 'none';
base-uri 'none';
frame-ancestors 'none';
report-to csp-endpoint
Reporting-Endpoints: csp-endpoint="https://example.com/csp-reports"A policy can be trialed first with the Content-Security-Policy-Report-Only header: the browser does not enforce it and only reports violations. The W3C says CSP is not intended as a first line of defense against content injection; it is best used as defense in depth. As of October 2026, the W3C Recommendation is CSP Level 2, dated December 15, 2016, while Level 3 is still a Working Draft.
HttpOnly, SameSite and Trusted Types
- HttpOnly: According to MDN, this attribute forbids JavaScript from accessing the cookie and mitigates XSS attacks. The cookie is still sent with script-initiated requests, though: a script cannot read the session cookie, but it can still send requests as the user. According to OWASP, cookie attributes do not address the root cause of the vulnerability.
- SameSite: Controls whether a cookie is sent with cross-site requests, using the values Strict, Lax or None; according to MDN, it provides some protection against CSRF.
- Trusted Types: MDN describes this API as a way to ensure that input has passed through a developer-defined transformation function before it reaches an API that might execute it, such as innerHTML. The require-trusted-types-for CSP directive stops plain strings from being passed to these APIs. The API does no sanitizing itself; that is the job of the policy the developer writes. According to MDN, the feature has worked across the latest browser versions since February 2026.
XSS vs. CSRF
OWASP defines CSRF (cross-site request forgery) as an attack that forces an end user to execute unwanted actions on a web application in which they are currently authenticated. It targets state-changing requests, because the victim, not the attacker, receives the response. In XSS, by contrast, the attacker's code runs inside the site and can reach the page itself, which is why OWASP's CSRF prevention cheat sheet reminds readers that XSS can defeat all CSRF mitigation techniques. Against CSRF, the cheat sheet recommends a framework's built-in protection and the synchronizer token pattern, and it treats SameSite only as an additional layer.
How to detect XSS
- Code review and SAST: CISA and the FBI recommend code reviews and aggressive adversarial product testing. According to OWASP, static analysis (SAST) tools can run as part of continuous integration but produce high numbers of false positives (see our CI/CD article).
- DAST and penetration testing: DAST tools scan applications, normally from the outside. According to OWASP's testing guide, automated testing has only very limited success with DOM-based XSS, so client-side code has to be reviewed by hand. We describe scanning on our vulnerability scan page and manual testing in our penetration testing article.
- WAF: According to OWASP, WAFs are unreliable for preventing XSS: they can be bypassed and miss XSS that runs only in the browser. They can still act as a virtual patch until a permanent fix ships (see our WAF article).
We cover protection at the application layer in our application security (WAF) service and broader assessments in our security assessment service.
Frequently asked questions
What does XSS mean? XSS stands for cross-site scripting. It means a malicious script planted on a website runs in other users' browsers.
How does an XSS vulnerability occur? It occurs when an application puts data from an untrusted source into a page without encoding or sanitizing it.
What is CSRF, and how is it different from XSS? CSRF makes a logged-in user's browser perform an action the user did not intend, but the attacker cannot see the response. In XSS, the code runs inside the site and can even defeat CSRF defenses.
What is Content Security Policy (CSP)? It is a security mechanism through which a site tells the browser, in an HTTP header, which scripts may run. It does not replace output encoding.
Does a WAF prevent XSS attacks? Not on its own. According to OWASP, WAFs can be bypassed and cannot see DOM-based XSS; the permanent fix is correcting the code.
Sources
- OWASP, Cross Site Scripting (XSS): definition, how XSS occurs, reflected and stored types, consequences of an attack
- OWASP, Types of XSS: Server XSS and Client XSS terms and the main defense for each
- OWASP, DOM Based XSS: definition of DOM-based XSS and data that never reaches the server
- MITRE, CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting'): definition of the weakness, the phishing note and mitigations (CWE 4.20)
- CWE, 2025 CWE Top 25 Most Dangerous Software Weaknesses and announcement: ranks of CWE-79 and CWE-352, dataset and period (December 11, 2025)
- OWASP, A05:2025 Injection: where XSS sits in the category and its CVE count
- CISA and FBI, Secure by Design Alert: Eliminating Cross-Site Scripting Vulnerabilities and CISA announcement: XSS as a preventable defect and recommendations for manufacturers (September 2024)
- OWASP, Cross Site Scripting Prevention Cheat Sheet: output encoding, framework risks, HTML sanitization, safe APIs, cookie attributes and the assessment of WAFs
- MDN, Cross-site scripting (XSS): what injected code can do
- React, Common components: the dangerouslySetInnerHTML warning
- Angular, Security: values marked as trusted with the bypassSecurityTrust functions
- MDN, Content Security Policy (CSP): strict CSP, nonces, unsafe-inline, Report-Only and the example headers
- W3C, Content Security Policy Level 3, CSP Level 3 publication history and CSP Level 2 publication history: definition of CSP, its defense-in-depth role and document status (Level 2 Recommendation, December 15, 2016; Level 3 Working Draft, September 16, 2026)
- MDN, Set-Cookie: the HttpOnly and SameSite attributes
- MDN, Trusted Types API and require-trusted-types-for: definition, enforcement through CSP and browser support (Baseline 2026)
- OWASP, Cross Site Request Forgery (CSRF): definition of CSRF and the requests it targets
- OWASP, Cross-Site Request Forgery Prevention Cheat Sheet: XSS defeating CSRF defenses, recommended defenses and SameSite
- OWASP, Source Code Analysis Tools and Vulnerability Scanning Tools: definitions of SAST and DAST tools
- OWASP, Web Security Testing Guide v4.2: stored XSS test (WSTG-INPV-02) and DOM-based XSS test (WSTG-CLNT-01)
- OWASP, Virtual Patching Cheat Sheet: definition of virtual patching
- How we run this layer: application security (WAF)