Cross-site scripting (XSS) is one of the most common vulnerabilities in web applications. It allows attackers to inject malicious scripts into webpages viewed by other users. This tutorial explains how XSS works and how to prevent it in your applications.
XSS occurs when untrusted data is inserted into a web page without proper validation or escaping. There are three types:
Use proper encoding when inserting data into HTML:
<!-- BAD -->
<div>Welcome, <span>{{username}}</span></div>
<!-- GOOD -->
<div>Welcome, <span>{{escape(username)}}</span></div>
Escape:
<
becomes <
>
becomes >
&
becomes &
"
becomes "
Modern frameworks (like React, Angular, Django) auto-escape output to prevent XSS by default.
Never embed user input directly into JavaScript code or event handlers:
<!-- DANGEROUS -->
<button onclick="doSomething('{{ user_input }}')">Click</button>
CSP restricts where scripts can load from. Example header:
Content-Security-Policy: default-src 'self'; script-src 'self'
Only allow safe values, especially for rich content fields. Use libraries like DOMPurify to clean HTML if needed.
Scan your web app with tools like OWASP ZAP or Burp Suite. Make sure all dynamic content is encoded and never trust user input.