Networking basics, Preventing Cross-Site Scripting (XSS)

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.

What is XSS?

XSS occurs when untrusted data is inserted into a web page without proper validation or escaping. There are three types:

  • Stored XSS: Malicious script is saved in the database and displayed to users.
  • Reflected XSS: Script is embedded in a URL and executed when the link is clicked.
  • DOM-based XSS: Client-side JavaScript processes data and renders unsafe HTML.

Step 1: Escape User Input in HTML

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 &lt;
  • > becomes &gt;
  • & becomes &amp;
  • " becomes &quot;

Step 2: Use Secure Templates and Frameworks

Modern frameworks (like React, Angular, Django) auto-escape output to prevent XSS by default.

Step 3: Avoid Inline JavaScript with User Data

Never embed user input directly into JavaScript code or event handlers:

<!-- DANGEROUS -->
    <button onclick="doSomething('{{ user_input }}')">Click</button>

Step 4: Use Content Security Policy (CSP)

CSP restricts where scripts can load from. Example header:

Content-Security-Policy: default-src 'self'; script-src 'self'

Step 5: Validate and Sanitize Input

Only allow safe values, especially for rich content fields. Use libraries like DOMPurify to clean HTML if needed.

Next Steps

Scan your web app with tools like OWASP ZAP or Burp Suite. Make sure all dynamic content is encoded and never trust user input.