XSS Explained: Types, Code Examples and How to Prevent It
Security TestingHetz Team

XSS Explained: Types, Code Examples and How to Prevent It

Cross-site scripting explained: reflected, stored and DOM-based XSS, a code example of the bug and its fix, how to test for it safely and the defenses that work.

Cross-site scripting, usually called XSS, happens when an application puts data from a user into a web page without making it safe first. The browser then reads that data as code and runs it, in the context of the real site and the real user. It is one of the oldest web vulnerabilities and still one of the most common, because the mistake is easy to make in any feature that displays something a user typed.

This guide explains the three types of XSS, shows a short code example of the bug and its fix, describes where XSS hides in modern apps, and explains how to test for it safely. For the broader category, see our OWASP Top 10 explainer, where XSS sits under injection.

What XSS Is

Think of the browser as a reader that trusts the page it receives. It treats everything inside the page as either text or markup, and it runs any script it finds. If an application writes a user's name into the page as markup, a name that contains markup becomes part of the page, and a script inside it runs.

The result is that the attacker's code runs with the same access as the page. It can read what the user sees, send requests as the user, change settings and, if cookies are not protected, read the session. That is why XSS is treated as a serious issue, even though the entry point is often a simple text field.

The Three Types

TypeWhere the payload livesWho is affected
ReflectedIn the request, echoed back in the response, often through a crafted linkThe person who opens the link
StoredIn the application's database, such as a comment, profile or file nameEveryone who views the stored data
DOM-basedIn client-side code that writes untrusted data into the pageWhoever loads the affected page with the payload

Stored XSS is the most serious. A payload saved once can run for every visitor, and it can reach administrators who review user content in a back office. Reflected XSS usually needs a victim to click a link, which limits its reach but still matters for phishing. DOM-based XSS is easy to miss, because the server never sees the payload, and it appears only in browser code.

A Code Example: The Bug and the Fix

Here is a simple browser example, a greeting that uses a name from the page's URL. The vulnerable version writes the name as HTML.

// Vulnerable: the browser parses whatever the name contains as HTML
document.getElementById("greeting").innerHTML = "Welcome back, " + name;

// Fixed: the value is inserted as text and never parsed as markup
document.getElementById("greeting").textContent = "Welcome back, " + name;

The difference is one property. innerHTML tells the browser to parse the string as markup, so anything in it, including a script-bearing tag, becomes live. textContent tells it to treat the string as text, so any angle brackets are shown as characters. The second version is safe for this use, and it is the default choice whenever you do not need the content to contain formatting.

The same principle applies on the server. Template engines that escape output by default protect you as long as you use the escaped form. A raw output tag, which many templates provide for trusted HTML, is where the bug usually appears.

Where XSS Hides in Modern Apps

Most XSS in current applications is not in a plain text field. It hides in features that display user content in a richer way:

  • Rich text and markdown. Editors and comment systems that render HTML or markdown without a sanitizer.
  • Profile and display names. Shown in dashboards, emails, invoices and admin pages, sometimes in places the developer forgot.
  • File names and uploads. A file name displayed in a list, or an SVG image that contains script and is served as an active document.
  • URL parameters. Search terms, error messages and redirect values that are reflected into the page.
  • Admin views. Back-office tools that display user content, often with fewer protections and more privileges.
  • Emails and notifications. HTML templates that include user data, which may be rendered in a mail client or in a web view.
  • Client-side routing. Single-page apps that read a value from the URL and write it into the DOM.

Each of these is a place where an attacker's text can cross from data into code. When testing, look for every spot where something a user typed is displayed to someone else.

How to Test for XSS Safely

The safest way to test is with harmless markers. Submit a unique string that contains special characters, such as a random token followed by angle brackets and quotes, into each field and parameter. Then look at the page and check two things: whether the string appears exactly as typed, and whether the browser treats any part of it as markup. If the characters appear as plain text, the data is escaped. If an element appears that you did not type, or a tag changes the layout, you have found a problem.

Repeat the test wherever the data appears, not only on the page where it was entered. A comment that looks safe on the public page may be rendered unescaped in the admin panel or in an email. Check admin views and exports too, because they are often built by a different team with different assumptions.

Use test payloads only on systems you own or are authorized to test, and avoid anything that could affect real users, such as stored payloads on a live customer-facing page. Write down the exact input, the place it was shown and the result, so the developer can reproduce it.

How to Prevent XSS

Most prevention comes down to a few habits that work together:

  1. Escape output for the context. Text in HTML, text in an attribute, a URL and a script block each need different escaping. Use the escaping your framework provides, and do not write your own.
  2. Use safe DOM APIs. Prefer textContent and framework bindings over innerHTML. If you must render HTML, pass it through a vetted sanitizer first.
  3. Sanitize rich content. When users can post formatted text, use a well-maintained HTML sanitizer with a strict allowlist of tags and attributes.
  4. Validate URLs. Accept only expected schemes, such as https, for links and redirects. A link that starts with javascript: is script, not a link.
  5. Set a Content-Security-Policy. A policy that only allows scripts from your own sources blocks most injected scripts from running, which limits the damage even when a bug slips through. The MDN guide to Content-Security-Policy explains the directives.
  6. Protect cookies. Mark session cookies HttpOnly so scripts cannot read them directly, as covered in our authentication security checklist.

The OWASP Cross-Site Scripting Prevention Cheat Sheet goes through these rules by context, and it is a good reference for code reviews.

Why Stored XSS Deserves Attention

A stored payload is a long-lived risk. It may be created by an ordinary user, sit in the database for months, and run the first time an administrator opens a list. Because administrators often have more access, the impact can be much larger than the input suggests. A name field that looks harmless to the developer can become the most important finding in a report when it reaches the admin panel.

This is also why prevention should be applied at the point of display, not only at the point of input. Input validation helps, but the reliable rule is to escape or sanitize every time data is rendered, for every viewer, in every context.

Common Misconceptions

"Our site only stores text, so XSS cannot happen." Text becomes markup at the moment it is displayed. If the display step parses it as HTML, plain text stored in a database is enough to cause the problem.

"Only the input form needs filtering." Input filters are easy to bypass, and they cannot know every place the data will appear later. Encoding at output, where the browser receives the value, is the reliable control.

"Blocking one character or tag is enough." Attackers find other tags, attributes and encodings. A blocklist of known bad strings is fragile, while an allowlist of safe output and a sanitizer with a strict configuration holds up much better.

Where Hetz Fits

Hetz tests for XSS as part of an automated run on the live product. Agents submit test markers to every input the product accepts, follow each value to every page where it is displayed, and check the rendered result, including views that only admins see. Only findings with a proven reflection or execution path reach the report, each with the exact request, the place where it runs, a fix for your stack and a retest after the change. Our web application penetration testing page explains the scope.

For more on the surrounding checks, read web application security testing, and for the access control side of the same kind of data exposure, read IDOR and broken access control.

Next steps

This week, list every place in your product where user-written text is displayed to another person, including admin screens and emails. Test each with a harmless marker and fix any that render as markup. Then add a Content-Security-Policy to limit the damage of future mistakes. You can see how an automated run covers these checks on the home page, review pricing, or start a scan.

FAQ

Frequently asked questions

Keep reading