What Is XSS? Cross-Site Scripting Examples & How to Prevent XSS Attacks
Learn what XSS is, its types, and how to prevent XSS with a worked DVWA example, context-aware defenses, testing tips, and a cheat sheet.
When a Website Turns Against Its Visitors
A forum comment, search field, profile, or support ticket becomes dangerous when an application treats user-controlled data as executable markup. In an authorized lab, <script>alert(1)</script> is a harmless proof that the browser interpreted data as code. In a real XSS attack, the script runs within the vulnerable site's origin and can interact with accessible page content, browser storage, and authenticated application functions.
Impact of XSS
XSS can enable session abuse, credential phishing, keystroke capture, unauthorized account actions, data exposure, redirects, defacement, or malware delivery. Stored XSS may affect every user who opens a compromised page. HttpOnly cookies can prevent direct cookie reads, but injected code may still submit authenticated requests or steal data displayed in the page.
All payloads in this guide use alert(1) and are intended only for isolated labs or applications you are authorized to test.
What Is XSS?
Cross-site scripting (XSS) is a web vulnerability in which untrusted data becomes executable browser content on a trusted site. The browser then runs that content in the site's origin, allowing it to read accessible page data, alter the interface, or make authenticated requests as the victim.
The weakness normally appears at a boundary where data becomes HTML, an attribute, JavaScript, CSS, or a URL. It is called "cross-site" for historical reasons, but an exploit does not need to involve two websites. In the OWASP Top 10 2021, XSS is included under A03: Injection rather than listed as the standalone A7 category used in 2017.
Why XSS Still Matters in 2027
XSS is one of the oldest web vulnerabilities, yet it still shows up in real applications every year. Modern frameworks escape output by default, but applications still combine user data with HTML in custom components, server-rendered pages, markdown renderers, admin dashboards, and single-page applications that read data from the URL or browser storage. Every one of those paths is a potential sink. Bug bounty programs still pay for stored XSS because a single saved payload can reach every user who opens the affected page, including administrators. The fix has not changed in years — encode output for its context — but the number of places where a developer must apply it keeps growing as applications add more ways to render user data.
XSS Attack Vectors
Common Injection Points
Potential entry points include:
postMessage data, and browser storageFor DOM-based XSS, trace data from a source such as location.hash to a dangerous sink such as innerHTML, outerHTML, insertAdjacentHTML, document.write, or eval.
const value = decodeURIComponent(location.hash.slice(1));
document.querySelector('#greeting').innerHTML = value;
The safer version treats the value as text:
const value = decodeURIComponent(location.hash.slice(1));
document.querySelector('#greeting').textContent = value;
A value being stored or reflected does not automatically make it executable. Exploitation depends on the final rendering context and how the browser parses it.
How to Prevent XSS Attacks
The central rule for how to prevent XSS is to keep untrusted data separate from executable code. Apply the following OWASP-style prevention rules at the final output location.
textContent.&, <, >, ", and ' into entities before rendering plain text between tags. Template auto-escaping normally handles this when it remains enabled.onclick or in attributes whose values become executable.javascript: URL safe. If the completed URL enters an HTML attribute, attribute-encode it as well.Supporting Layers
HttpOnly, Secure, and with an appropriate SameSite value.Worked Example: Finding and Fixing Reflected and Stored XSS on a DVWA Lab
Use only an isolated, locally hosted DVWA installation that you own. Set DVWA Security to Low, understanding that this mode deliberately removes defenses. Every input, response, and result below is illustrative; labels can differ between DVWA releases.
Reflected XSS
Open XSS (Reflected) and submit this in its search-style name field.
Illustrative reflected input:
<script>alert(1)</script>
If an alert appears immediately after submission, the input reached an executable HTML context. A vulnerable implementation may resemble the following.
Illustrative vulnerable server pattern:
echo '<p>Results for: ' . ($_GET['name'] ?? '') . '</p>';
Illustrative vulnerable response:
<p>Results for: <script>alert(1)</script></p>
The response embeds the value as markup, so the browser creates and executes a script element.
Stored XSS
Open XSS (Stored), enter a harmless name, and place <script>alert(1)</script> in the comment or message field.
Illustrative expected result: the record is saved, and the alert appears whenever an affected user opens the comments page. Retesting with a separate authorized browser profile demonstrates that execution is tied to the stored record rather than only to the submitting request.
Fixing Both Flaws
Encode plain-text values when they are rendered, including values retrieved from the database. Add a restrictive CSP as a backup for a missed sink.
Illustrative fixed PHP excerpt:
<?php
$nonce = base64_encode(random_bytes(16));
header(
"Content-Security-Policy: default-src 'self'; script-src 'nonce-" .
$nonce .
"' 'strict-dynamic'; object-src 'none'; base-uri 'none'"
);
function h(string $value): string {
return htmlspecialchars(
$value,
ENT_QUOTES | ENT_SUBSTITUTE,
'UTF-8'
);
}
$name = $_GET['name'] ?? '';
echo '<p>Results for: ' . h(is_string($name) ? $name : '') . '</p>';
echo '<p>' . nl2br(h($commentFromDatabase)) . '</p>';
?>
<script nonce="<?= h($nonce) ?>" src="/assets/app.js"></script>
$commentFromDatabase represents the value read from storage. Calling htmlspecialchars when rendering converts markup-significant characters into entities. Applying nl2br afterward preserves line breaks without making the original comment executable.
Illustrative post-fix result: the page displays <script>alert(1)</script> as text, and no alert opens. The CSP also blocks unauthorized inline script execution, but it does not replace the encoding fix. Use a different encoder if the same value is later rendered in an attribute, URL, CSS, or JavaScript context.
The Three Types of XSS, Compared
| Type | Delivery | Persistence | Where the Fix Lives |
|---|---|---|---|
| Reflected XSS | Input is included in the immediate server response, often through a crafted query or form request | Normally limited to that request | Server template, response builder, and the final output context |
| Stored XSS | Input is saved in a database, comment, profile, ticket, or log and rendered later | Persists until removed or changed | Every view that renders the stored value, plus safe rich-content sanitization where required |
| DOM-based XSS | Client-side code moves attacker-controlled data from a browser source into an unsafe sink | Depends on the source; it can be transient or stored | Client-side data flow and DOM API usage |
These labels describe different dimensions. A stored value can eventually trigger through a DOM sink, while a reflected response can contain client-side code that performs the unsafe rendering.
Blind XSS is usually stored XSS that executes in a different interface, such as an administration or support dashboard. The submitter cannot directly see the result. Test this only with explicit permission and a controlled lab or authorized reviewer session.
Context-Aware Output Encoding
Choose an encoder for the parser that will receive the value.
| Render Context | Preferred Defense |
|---|---|
| HTML text between tags | Framework auto-escaping, HTML encoding, or textContent |
| Quoted HTML attribute | Attribute encoder, fixed attribute name, and quotes |
| JavaScript data | Avoid inline generation; otherwise use trusted JSON serialization or a JavaScript encoder |
| CSS value | Avoid dynamic CSS or use a CSS encoder with strict value allowlists |
| URL component | Validate the scheme and destination, then encode the individual component |
| Rich HTML | Sanitize with a maintained allowlist sanitizer |
The following examples encode a value for HTML text, not every possible context.
Python
import html
safe = html.escape(user_input, quote=True)
PHP
$safe = htmlspecialchars(
$userInput,
ENT_QUOTES | ENT_SUBSTITUTE,
'UTF-8'
);
Node.js
const he = require('he');
const safe = he.encode(userInput);
Java
import org.owasp.encoder.Encode;
String safe = Encode.forHtml(userInput);
The OWASP Java Encoder also provides context-specific methods such as forHtmlAttribute, forJavaScriptBlock, and forCssString.
Why the Wrong Encoding Fails
Each browser parser assigns different meaning to quotes, backslashes, percent signs, and entity references. HTML encoding a value inside JavaScript may still produce valid executable JavaScript after HTML parsing. URL encoding does not reject a dangerous protocol, and JavaScript escaping does not make a value safe as HTML. Encode once, at the final sink, for the exact context.
For intentionally permitted HTML, sanitize before insertion:
container.innerHTML = DOMPurify.sanitize(untrustedHtml);
Do not modify or concatenate untrusted markup after sanitization.
Content Security Policy That Actually Stops XSS
A nonce-based CSP authorizes specific script elements rather than every script from a broad host allowlist.
Content-Security-Policy: default-src 'self'; script-src 'nonce-BASE64_NONCE' 'strict-dynamic'; object-src 'none'; base-uri 'none'; require-trusted-types-for 'script'; trusted-types app
The server must generate a cryptographically unpredictable nonce for every response and place the same value on each approved script:
<script nonce="BASE64_NONCE" src="/assets/app.js"></script>
Never use the placeholder or a static nonce in production. In supporting browsers, 'strict-dynamic' allows a nonce-authorized root script to load its trusted dependencies. object-src 'none' disables plugin content, while base-uri 'none' prevents an injected base element from changing relative URL resolution.
Trusted Types, where supported, can require approved policies before values reach sinks such as innerHTML. A policy must sanitize or safely construct content; a pass-through policy defeats the purpose.
Test a policy with Content-Security-Policy-Report-Only before enforcement, review violations, and remove unnecessary inline code. CSP is defense in depth, not a substitute for output encoding or HTML sanitization.
Framework Protections: React, Angular, Vue
| Framework | Safe Default | Dangerous Holes | Safer Approach |
|---|---|---|---|
| React | Values rendered through JSX expressions are escaped | dangerouslySetInnerHTML, direct innerHTML, and unsafe third-party DOM code | Render normal JSX text or assign textContent; sanitize genuinely required HTML |
| Angular | Interpolation escapes values, and Angular sanitizes several property bindings | Native innerHTML, unsafe [innerHTML] use, and bypassSecurityTrustHtml or related trust bypasses | Prefer interpolation or [textContent]; narrowly review every trusted-value bypass |
| Vue | Mustache expressions and normal bindings are escaped | v-html, direct DOM manipulation, and compiling untrusted templates | Use mustache syntax or v-text; sanitize approved rich HTML before v-html |
Framework protection applies only while data stays inside safe rendering paths. Server-rendered bootstrap HTML, plugins, markdown renderers, and custom directives require separate review. Never compile user input as a component or template.
Testing for XSS
Manual Workflow
<script>alert(1)</script> or <img src=x onerror=alert(1)>.An alert proves browser code execution, but reflection alone does not. Conversely, CSP may block execution while an underlying injection flaw still exists.
Automated Tools
| Tool | Appropriate Use |
|---|---|
| Burp Suite | Use Proxy and Repeater for manual context analysis. Burp Scanner in Professional can actively test authorized targets. |
| XSStrike | Analyzes reflected parameters and their contexts and generates focused XSS tests. |
| OWASP ZAP | Crawls applications, passively reports issues, and can actively scan an authorized test environment. |
| Wapiti | Performs black-box crawling and module-based vulnerability testing, including XSS checks. |
Read the evidence rather than accepting a tool label. Reproduce the exact request, locate the reflection, inspect its context, and confirm whether controlled execution is possible. Scanner output that only finds an encoded reflection is commonly a false positive.
XSS vs CSRF vs SQL Injection
| Issue | What Is Injected or Forged | Where It Runs | Primary Fix |
|---|---|---|---|
| XSS | Browser-executable markup or script content | Victim's browser in the vulnerable origin | Context-aware encoding, sanitization, safe DOM APIs, and CSP |
| CSRF | A forged state-changing request; code injection is not required | Request is sent by the victim's browser and processed by the server | CSRF tokens, SameSite cookies, Origin checks, and reauthentication |
| SQL injection | SQL syntax mixed into a database query | Database server | Parameterized queries, safe ORM APIs, and least privilege |
A CSRF token does not fix XSS, and prepared SQL statements do not protect an HTML sink. XSS may also expose or use CSRF tokens available to the compromised page, making XSS prevention essential.
XSS Cheat Sheet
Use these proofs only in your own lab or an explicitly authorized test environment.
Laboratory Payloads
| Context Being Tested | Proof-of-Concept |
|---|---|
| HTML element content | <script>alert(1)</script> |
| HTML parser and event handler | <img src=x onerror=alert(1)> |
| SVG event handling | <svg onload=alert(1)> |
| Quoted attribute breakout | "><img src=x onerror=alert(1)> |
| Link URL requiring a click | <a href="javascript:alert(1)">test</a> |
| Data embedded inside a script element | </script><script>alert(1)</script> |
These are diagnostic probes, not universal payloads. A result depends on the exact parser context, browser controls, and application transformations.
Prevention Quick Reference
| Situation | Use |
|---|---|
| Displaying a username or comment as text | Auto-escaping or HTML encoding |
| Updating page text in JavaScript | textContent |
| Building a query parameter | URL API or component encoding, followed by attribute encoding if rendered |
| Allowing formatted comments | Maintained allowlist sanitizer |
| Creating scripts dynamically | Avoid user-controlled code; use nonce-based CSP |
| Protecting session cookies | HttpOnly, Secure, and appropriate SameSite settings |
| Returning JSON | Content-Type: application/json and X-Content-Type-Options: nosniff |
Troubleshooting XSS Problems
| Problem | What to Check |
|---|---|
| Payload shows as text | Encoding may be working correctly. Inspect the response and DOM before trying anything else. |
| Alert never fires | Confirm the payload matches the context, its event can occur, and CSP, Trusted Types, or a sandbox is not blocking it. |
| CSP blocks your own script | Ensure the server generated a fresh nonce and that the exact same nonce appears in the header and approved script element. |
| Stored payload is not triggering | Verify the record was saved, approved, and displayed in the view used by the intended authorized role. |
| WAF blocks the test | Do not evade it on a production system. Coordinate an allowlisted scanner address or reproduce the issue in staging. |
| Encoding bypass remains possible | Look for the wrong encoder, multiple decoding steps, mutation after encoding, or a different final render context. |
| DOM sink is not found | Search scripts for dangerous DOM APIs and use DevTools DOM breakpoints or debugger tracing to follow the value. |
| Scanner reports a false positive | Reproduce the request and distinguish harmless reflection from markup creation or executable browser behavior. |
Common Mistakes
script misses other elements, attributes, encodings, and DOM-based paths.'unsafe-inline' permissions undermine enforcement.Best Practices
Defense Checklist
eval, document.write, and unnecessary innerHTMLHttpOnly, Secure, and appropriate SameSite cookie flagsIs XSS Testing Legal?
Test only applications you own or systems for which you have explicit written permission. Authorization should identify the domains, accounts, techniques, schedule, and data-handling rules. A public website or bug bounty listing is not blanket permission beyond its published scope.
Do not test random websites, send crafted links to other users, or attempt to bypass production defenses without authorization. DVWA and other intentionally vulnerable local labs are safer places to practice.
Knowledge Check
Answers: 1. Each HTML, attribute, JavaScript, CSS, and URL parser interprets characters differently, so the wrong encoder can leave executable syntax. 2. Validate the protocol and destination, then encode the individual URL component and attribute-encode the completed URL if it enters HTML. 3. Stored XSS. 4. A reused or predictable nonce could authorize injected script elements instead of only scripts approved for that response. 5. dangerouslySetInnerHTML. 6. HttpOnly prevents JavaScript from reading the cookie directly, but XSS can still read page data, alter the interface, or submit authenticated requests. 7. The value must reach an executable browser context; an encoded or text-only reflection may be harmless. 8. Only when you own the application or have explicit authorization covering the target and testing activity.
Keep Learning
Summary
XSS turns a trusted website into a delivery mechanism for attacker-controlled code, and the browser cannot tell the attacker's script from the site's own. The three types — reflected, stored, and DOM-based — differ in delivery and persistence, but they share one root cause: untrusted data rendered as executable content. Prevent it by encoding output for its exact context, sanitizing only genuinely required rich HTML, letting frameworks escape by default, and adding a nonce-based CSP as defense in depth. Test every input in an authorized lab, fix the sink rather than the symptom, and retest after every change.
Frequently Asked Questions
Continue Learning
What Is CSRF? Cross-Site Request Forgery Examples & How to Prevent CSRF Attacks
What is CSRF? Learn how cross-site request forgery tricks your browser into unwanted actions, see real examples and a DVWA worked test, and follow 7 steps to prevent CSRF attacks with tokens, SameSite cookies and framework protection.
Web Security · IntermediateWhat Is SQL Injection? Types, Examples & How to Prevent SQL Injection Attacks
What is SQL injection? See real SQL injection examples, a worked DVWA lab test, and how to prevent SQL injection with parameterized queries.
Web Security · IntermediateAPI Hacking Guide: How to Test APIs for Security Flaws (BOLA, JWT & GraphQL)
Learn API hacking step by step: discover endpoints, test authentication and authorization, find BOLA flaws with a worked crAPI example, test JWTs and GraphQL, and report findings — with tools, a cheat sheet and a checklist.
Web Security · IntermediateWhat Is IDOR? Insecure Direct Object Reference Examples & How to Prevent IDOR Attacks
What is IDOR? See real insecure direct object reference examples, a worked lab test with Burp Suite, and how to prevent IDOR with server-side checks.
Related Security Tools
XSStrike
XSStrike is an advanced Cross-Site Scripting (XSS) detection suite. It features intelligent payload generation, context analysis, a powerful fuzzing engine, and built-in WAF detection and bypass capabilities.
Web ApplicationXSSer
XSSer (Cross Site Scripting Exploiter) is an automatic framework to detect, exploit, and report XSS vulnerabilities in web applications. It contains features to bypass several filters and various options for automated payload generation.
Web SecuritySecurity Headers Checker
Check HTTP security headers (CSP, HSTS, X-Frame-Options, X-XSS-Protection, Referrer-Policy, and more) with security scoring.