Cross-Site Scripting (XSS) allows attackers to inject malicious scripts into web pages viewed by other users. When a browser executes the injected script, the attacker can steal session tokens, redirect users to malicious sites, deface the page, or perform actions on behalf of the victim. XSS is the most common web application vulnerability and appears in three forms: Stored XSS, Reflected XSS, and DOM-based XSS.
AI code assistants routinely generate DOM manipulation code using innerHTML instead of textContent, and React code with dangerouslySetInnerHTML for rendering dynamic content. When asked to "display user comments on the page" or "render HTML content from an API," AI tools default to the most straightforward approach — which is almost always the insecure one. AI models also frequently generate Express.js endpoints that reflect query parameters directly into HTML responses without encoding, creating reflected XSS vulnerabilities.
// React — AI-generated vulnerable code
function UserComment({ comment }: { comment: string }) {
// VULNERABLE: renders unsanitized HTML from user input
return (
<div
dangerouslySetInnerHTML={{ __html: comment }}
/>
);
}
// Vanilla JS — AI-generated vulnerable code
function displayResults(query: string) {
const container = document.getElementById("results");
// VULNERABLE: innerHTML with unsanitized input
container!.innerHTML = `
<h2>Results for: ${query}</h2>
<p>Searching...</p>
`;
}// React — sanitized rendering (secure)
import DOMPurify from "dompurify";
function UserComment({ comment }: { comment: string }) {
// SECURE: sanitize HTML before rendering
const clean = DOMPurify.sanitize(comment);
return (
<div
dangerouslySetInnerHTML={{ __html: clean }}
/>
);
}
// Vanilla JS — textContent (secure)
function displayResults(query: string) {
const container = document.getElementById("results");
const heading = document.createElement("h2");
// SECURE: textContent does not parse HTML
heading.textContent = `Results for: ${query}`;
container!.replaceChildren(heading);
}CodeShield uses multi-layer static analysis to detect cross-site scripting (xss) vulnerabilities across your entire codebase:
CodeShield detects cross-site scripting (xss) and 5+ other vulnerability types across your entire codebase. Auto-fix with AI in one click.
Scan Your Repos Free