XSS Cross-Site Scripting Defense Guide: Frontend Security
Cross-Site Scripting (XSS) is one of the most common web vulnerabilities, consistently in OWASP Top 10 since 2010. XSS allows attackers to inject malicious scripts into websites, stealing sensitive information, hijacking sessions, or defacing pages.
Types of XSS
Reflected XSS
Malicious script embedded in URL parameters. Server reflects unescaped script back to browser.
Attack flow: Attacker crafts URL with <script>, user clicks link, server renders script directly.
Stored XSS (Most Dangerous)
Malicious script stored on server (database, comments, profiles). Executes for every page visitor.
DOM-based XSS
Attack happens entirely client-side via unsafe DOM manipulation (innerHTML, document.write).
Defense Strategies
1. Output Encoding (Most Critical)
| Context | Encoding | Example |
|---|---|---|
| HTML tag content | HTML entities | <, > |
| HTML attribute | Attribute encoding | " |
| JavaScript string | Unicode escape | < |
| URL parameter | URL encoding | %3Cscript%3E |
2. Content Security Policy (CSP)
Browser-level defense. Even if code is injected, CSP blocks execution.
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.com
3. Framework Built-in Protection
- React: JSX auto-escapes output
- Vue: Template interpolation {{ }} auto-escapes
- Angular: Built-in DOM Sanitizer
4. HttpOnly Cookies
Set-Cookie: sessionid=xxx; HttpOnly; Secure; SameSite=Strict
Detection Tools
| Tool | Type | Features |
|---|---|---|
| OWASP ZAP | Open source | Auto XSS scanning |
| Burp Suite | Commercial | Professional testing |
| XSStrike | Open source | Advanced XSS detection |
Checklist
- All user input properly output-encoded?
- Strict CSP configured?
- HttpOnly cookies set?
- Avoid innerHTML, document.write?
- Libraries updated (no known XSS CVEs)?
- eval() disabled?
Summary
No silver bullet for XSS. Defense in depth: output encoding + CSP + framework protections. Start with CSP (blocks most XSS) and code review focus on output handling.