XSS
How injected scripts run in the browser and how to stop them
Overview
Cross-Site Scripting (XSS) happens when an attacker injects JavaScript that runs in another user's browser, often to steal session cookies or perform actions as that user. It occurs when untrusted data is written into a page without being encoded. The core fix is to encode output for its context and avoid inserting raw HTML.
Syntax / Usage
The vulnerability appears when user input is placed directly into the DOM. Prefer safe APIs like textContent, and let frameworks escape values for you.
// VULNERABLE: interprets input as HTML/script
const name = new URLSearchParams(location.search).get("name");
document.getElementById("greeting").innerHTML = "Hi " + name;
// ?name=<img src=x onerror=alert(document.cookie)>
// SAFE: treats input as plain text
document.getElementById("greeting").textContent = "Hi " + name;
Examples
In React, avoid dangerouslySetInnerHTML; JSX escapes text by default:
// Safe — React escapes the value
function Greeting({ name }) {
return <h1>Hi {name}</h1>;
}
If you must render HTML, sanitize it first with a trusted library:
import DOMPurify from "dompurify";
element.innerHTML = DOMPurify.sanitize(userHtml);
Add a Content Security Policy header as a strong second layer of defense:
Content-Security-Policy: default-src 'self'; script-src 'self'
Common Mistakes
- Using
innerHTML,document.write, orevalwith user-supplied data - Reaching for
dangerouslySetInnerHTMLwithout sanitizing input - Trusting data from URLs, form fields, or APIs as already safe
- Relying only on input filtering instead of output encoding
- Skipping a Content Security Policy that would blunt injected scripts
See Also
web-security-fundamentals web-security-csrf web-security-owasp-top-ten