Reflected Cross-Site Scripting (XSS) occurs when user input is immediately returned by a web application without proper sanitization or encoding. The malicious script is "reflected" off the web server in the response.
In this lab, we use innerHTML to display user input directly, which allows HTML and
JavaScript to be executed in the browser context.
Copy and paste these into the input field to see the vulnerability in action:
<img src=x onerror=alert('XSS')>
<script>alert('Reflected XSS!')</script>
<img src=x onerror="alert(document.cookie)">
Vulnerable Code:
// โ VULNERABLE: Using innerHTML with user input
const output = document.getElementById('output');
output.innerHTML = 'Welcome, ' + userInput + '!';
The problem: innerHTML parses the string as HTML, so any HTML tags or JavaScript
in the user input will be executed.
Secure Code:
// โ
SECURE: Using textContent instead
const output = document.getElementById('output');
output.textContent = 'Welcome, ' + userInput + '!';
// โ
SECURE: Or create text node
const textNode = document.createTextNode(userInput);
output.appendChild(textNode);
// โ
SECURE: Or use DOMPurify library
const clean = DOMPurify.sanitize(userInput);
output.innerHTML = 'Welcome, ' + clean + '!';
textContent instead of innerHTML for user input