What is XSS (Cross-Site Scripting) and how do you prevent it?
XSS occurs when an attacker injects malicious JavaScript into a page that is then executed in another user's browser, giving the attacker access to cookies, tokens, and the DOM.
Three types:
- Stored XSS — malicious script is saved in the database (e.g., a comment) and served to every user who views it.
- Reflected XSS — script is embedded in a URL, reflected in the response (e.g., search results page).
- DOM-based XSS — client-side JS reads attacker-controlled data (URL hash, postMessage) and writes it to the DOM unsafely.
Prevention:
- Never use
innerHTML,dangerouslySetInnerHTML, ordocument.writewith untrusted data. React auto-escapes by default — this is why it's safer. - Output encoding — HTML-encode user content before rendering it.
- Content Security Policy (CSP) — restricts which scripts can execute; blocks inline scripts.
- Sanitize HTML input — if you must allow rich text, use DOMPurify.
import DOMPurify from 'dompurify';
// Safe: sanitize before dangerouslySetInnerHTML
const clean = DOMPurify.sanitize(userHtml);
<div dangerouslySetInnerHTML={{ __html: clean }} />