Security

JavaScript XSS: How It Works and How to Fix It

XSS attacks inject malicious scripts into pages viewed by other users. JavaScript apps are particularly exposed when rendering user input directly into the DOM.


❌ Vulnerable: innerHTML with User Input

const q = new URLSearchParams(window.location.search).get('q');
document.getElementById('results').innerHTML = `<h2>Results for: ${q}</h2>`;

✅ Safe Fix

const q = new URLSearchParams(window.location.search).get('q');
const heading = document.createElement('h2');
heading.textContent = `Results for: ${q}`;
document.getElementById('results').appendChild(heading);
💡

Pro tip: Use textContent instead of innerHTML for user input. For rich HTML, use DOMPurify: element.innerHTML = DOMPurify.sanitize(userHtml).

Paste this code into LearnCodeGuide

Detect JavaScript vulnerabilities and bugs automatically with AI-powered analysis.

Analyze JavaScript Code →

Related Guides

Javascript Sql InjectionJavascript CsrfTypescript Xss