π 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)