DEV Community

Cover image for Cross-Site Scripting (XSS) Prevention
Kiran
Kiran

Posted on

Cross-Site Scripting (XSS) Prevention

πŸ” 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.

WebSecurity #XSS #Frontend #JavaScript #ReactJS #CyberSecurity #InterviewPrep #EngineeringMindset

Top comments (0)