0
0
Flaskframework~5 mins

XSS prevention in templates in Flask

Choose your learning style9 modes available
Introduction

XSS prevention stops bad code from running in your web pages. It keeps users safe from hackers who try to steal information or break your site.

When showing user comments or messages on a webpage
When displaying data that comes from outside your app, like form inputs
When including any text that users can change or add
When building pages that mix code and user content
When you want to keep your website secure and trustworthy
Syntax
Flask
{{ user_input }}
Flask templates automatically escape variables inside {{ }} to prevent XSS.
Use the |safe filter only if you trust the content and want to allow HTML.
Examples
This shows user input safely by escaping HTML special characters.
Flask
{{ user_input }}
This tells Flask to trust the input and render HTML tags as code (use carefully).
Flask
{{ user_input|safe }}
You can explicitly turn on autoescaping for a block of template code.
Flask
{% autoescape true %}{{ user_input }}{% endautoescape %}
Sample Program

This Flask app shows a form where users can type comments. When submitted, it displays the comment safely by escaping any HTML tags. This stops harmful scripts from running.

Flask
from flask import Flask, render_template_string, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    user_input = ''
    if request.method == 'POST':
        user_input = request.form.get('comment', '')
    template = '''
    <html lang="en">
    <head><title>XSS Prevention Demo</title></head>
    <body>
      <h1>Leave a Comment</h1>
      <form method="post">
        <textarea name="comment" rows="4" cols="40"></textarea><br>
        <button type="submit">Submit</button>
      </form>
      <h2>Your Comment:</h2>
      <div>{{ user_input }}</div>
    </body>
    </html>
    '''
    return render_template_string(template, user_input=user_input)

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Flask's Jinja2 template engine escapes variables by default to protect against XSS.

Only use the |safe filter if you are sure the content is safe and trusted.

Always validate and sanitize user input on the server side as an extra safety step.

Summary

XSS prevention keeps your website safe from harmful scripts.

Flask templates escape user data automatically inside {{ }}.

Be careful when using |safe to avoid security risks.