🔐 Cross-Site Scripting (XSS) Prevention — What Every Frontend Dev Must Know
XSS is one of the most common web attacks.
👉 It allows attackers to run malicious JavaScript in your app
👉 Can steal cookies, tokens, and user data
🧠 What is XSS?
Example attack:
<script>stealCookies()</script>
If your app renders this → attacker code runs ❌
⚠️ Types of XSS
1️⃣ Stored XSS → saved in DB
2️⃣ Reflected XSS → comes from URL/input
3️⃣ DOM-based XSS → happens in browser
🚨 How XSS Happens
👉 Rendering untrusted input directly
div.innerHTML = userInput; // ❌ dangerous
🛡️ How to Prevent XSS
1️⃣ Escape / Sanitize Input
✔ Never trust user input
✔ Use libraries like DOMPurify
2️⃣ Avoid Dangerous APIs
❌ innerHTML
❌ dangerouslySetInnerHTML in React
✔ Use safe rendering ({data} in JSX)
3️⃣ Use Content Security Policy (CSP)
Content-Security-Policy: script-src 'self'
👉 Blocks unauthorized scripts
4️⃣ Secure Cookies
✔ Use httpOnly
✔ Use Secure flag
👉 Prevents JS from accessing cookies
5️⃣ Validate on Backend Frontend is not enough.
✔ Always sanitize on server too
6️⃣ Avoid Inline Scripts
❌ alert()
✔ Use external JS files
💡 Real Impact
XSS can:
- Steal JWT tokens
- Hijack sessions
- Perform actions as user
👉 It’s a serious production risk
🚨 Interview Trap
❌ “React apps are safe from XSS”
✔ React escapes by default, but unsafe APIs can still break it
🎯 Interview One-Liner
XSS is a vulnerability where malicious scripts are injected into a web app, and it can be prevented by sanitizing input, avoiding unsafe DOM APIs, and enforcing CSP.
Top comments (0)