Security

XSS in Python Flask: Example and Fix

Cross-site scripting (XSS) allows attackers to inject malicious scripts into pages viewed by other users. Flask apps that render user input directly are vulnerable.


❌ Vulnerable Flask Route

@app.route('/search')
def search():
    query = request.args.get('q', '')
    return f'<h1>Results for: {query}</h1>'

✅ Secure Fix

from markupsafe import escape

@app.route('/search')
def search():
    query = escape(request.args.get('q', ''))
    return render_template_string('<h1>Results for: {{ q }}</h1>', q=query)
💡

Pro tip: Use markupsafe.escape() or Jinja2 auto-escaping. Never return raw user input as HTML.

Paste this code into LearnCodeGuide

Detect Python vulnerabilities and bugs automatically with AI-powered analysis.

Analyze Python Code →

Related Guides

Python Sql InjectionPython Command InjectionJavascript Xss