XSS Prevention
Cross-site scripting remains one of the most prevalent web vulnerabilities. This recipe covers output encoding, Content Security Policy, and safe DOM patterns that eliminate injection surfaces in modern web applications.
1. Output Encoding
Encode all user-controlled data before rendering it into HTML. Use context-aware encoders — HTML entity encoding for element content, attribute encoding for attribute values, and JavaScript encoding when embedding data inside script blocks.
2. Content Security Policy
Deploy a strict CSP header that restricts script sources and disallows inline execution. Use nonce-based or hash-based allowlisting for any legitimate inline scripts your application requires.
3. Safe DOM APIs
Avoid innerHTML and document.write. Prefer textContent for plain text insertion and createElement with setAttribute for dynamic DOM construction.
4. Framework Guards
Modern frameworks auto-escape template expressions. React's JSX, Vue's mustache syntax, and Angular's interpolation all default to safe string rendering. Never bypass these guards with dangerouslySetInnerHTML or equivalent escape hatches without rigorous sanitization.