TL;DR
XSS (Cross-Site Scripting) lets attackers inject malicious code into your website. This guide shows you how to prevent it by properly sanitising user input and escaping output.
1. Understand the Problem
XSS happens when your website displays data provided by users without checking if it’s safe. An attacker could inject JavaScript code that steals cookies, redirects visitors, or changes the look of your site.
2. Input Validation & Sanitisation
- Validate on the Server: Never trust data from the client-side (browser). Always validate input on your server before processing it.
- Whitelisting is Best: If possible, define exactly what characters and formats are allowed in each field. Reject anything that doesn’t match. For example, if a field should only contain numbers, reject any letters or symbols.
- Sanitise Input: Remove or encode potentially harmful characters. This means stripping out HTML tags, JavaScript code, and other dangerous elements. Be careful with this – overly aggressive sanitisation can break legitimate functionality!
Example (PHP):
3. Output Encoding/Escaping
- Context Matters: How you escape output depends on where it’s being used (HTML body, attribute, URL, JavaScript).
- HTML Escaping: Use this for displaying data within HTML tags. Converts characters like < to <.
- Attribute Escaping: Needed when inserting data into HTML attributes.
- JavaScript Escaping: Essential if you’re putting user input directly into JavaScript code.
- URL Encoding: Use this for data in URLs.
Example (Python/Flask):
from flask import escape
@app.route("/user/")
def user_profile(username):
return f"Hello, {escape(username)}"
4. Content Security Policy (CSP)
CSP is a powerful security header that tells the browser which sources of content are allowed to load. This can significantly reduce the risk of XSS attacks.
- Set the Header: Configure your web server to send the
Content-Security-Policyheader. - Restrict Sources: Define rules for scripts, styles, images, and other resources. For example, you can allow scripts only from your own domain.
Example (Apache .htaccess):
Header set Content-Security-Policy "default-src 'self'"
5. Use a Framework
Modern web frameworks often have built-in XSS protection mechanisms. They automatically escape output and provide tools for sanitising input.
- React: Escapes data by default when rendering JSX.
- Angular: Uses Angular’s template engine which escapes data.
- Vue.js: Provides directives for safe HTML rendering.
6. Regular Security Audits
Regularly scan your website for vulnerabilities, including XSS. Use automated tools and manual testing.
- Static Analysis Tools: Find potential issues in your code without running it.
- Dynamic Application Security Testing (DAST): Test your application while it’s running to identify runtime vulnerabilities.

