Reflected XSS in Python HTML responses

Reflected XSS in Python HTML responses

Description

Reflected XSS can occur when a browser interprets request data as HTML or script. Check the response’s Content-Type first. Even a body that looks like JSON may be served as HTML.

Framework/API Default behavior HTML output
Django HttpResponse text/html unless configured otherwise Default constructor or content_type="text/html"
String returned by a Flask view Converted to a text/html response String return, make_response, or Response
Ordinary FastAPI return value Usually serialized as JSON Return HTMLResponse or Response(..., media_type="text/html"), or set response_class=HTMLResponse on the route
Starlette response Endpoint returns a Response object HTMLResponse or a Response with media_type="text/html"

Potential impact

An injected script can read sensitive page data or send requests with the user’s privileges. A forged login or payment form can collect what the user types.

Remediation

Prefer templates and safe response types

  • Use Django or Jinja templates with autoescaping enabled for HTML text and quoted ordinary attributes. Keep untrusted values out of safe, mark_safe, and Markup.
  • When the client does not need HTML, send the appropriate response type. In FastAPI, use an ordinary return value or JSONResponse for JSON and PlainTextResponse for plain text.
python
from fastapi import FastAPI
from starlette.responses import PlainTextResponse

app = FastAPI()

@app.get("/search")
async def search(q: str):
    return {"query": q}  # JSON response

@app.get("/preview", response_class=PlainTextResponse)
async def preview(q: str):
    return q

Encode for the output context

When constructing HTML directly, handle each value where you insert it.

  • For HTML text and quoted ordinary attributes, use html.escape(value, quote=True), markupsafe.escape, or django.utils.html.escape. Attribute values need quote escaping.
  • For a URL attribute, validate the scheme and destination, build the URL, then encode it for the HTML attribute.
  • For JavaScript data, use the framework’s script-safe JSON serialization facility.
  • Keep CSS rules and selectors, HTML comments, and tag names under application control.

Use a maintained sanitizer for rich HTML

If users need to write rich HTML, allow only the tags, attributes, and URL schemes the feature requires. Use nh3.Cleaner on the Python server or an up-to-date DOMPurify with a reviewed policy in the browser. Render the sanitized result without further concatenation or changes.

Bleach stopped receiving security fixes on 2026-06-05. Migrate existing uses to a maintained sanitizer.

python
import nh3

rich_html_cleaner = nh3.Cleaner(
    tags={"p", "strong", "em", "a"},
    attributes={"a": {"href", "title"}},
    url_schemes={"https"},
)

safe_html = rich_html_cleaner.clean(user_html)

Check target browser support before using Element.setHTML(). Calling setHTMLUnsafe() alone does not protect the output.

Examples

Before

Flask serves this string as HTML, so the browser can interpret query as markup.

python
from flask import Flask, request

app = Flask(__name__)

@app.get("/search")
def search():
    query = request.args.get("q", "")
    return f"<h1>검색 결과</h1><p>{query}</p>"

html.escape(q) encodes HTML text. Here q is inside a JavaScript string.

python
import html

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()

@app.get("/search")
async def search(q: str):
    return HTMLResponse(
        f"<script>const query = '{html.escape(q)}';</script>"
    )

After

The search.html template autoescapes query and displays it as paragraph text.

python
from flask import Flask, render_template, request

app = Flask(__name__)

@app.get("/search")
def search():
    query = request.args.get("q", "")
    return render_template("search.html", query=query)
html
<h1>검색 결과</h1>
<p>{{ query }}</p>

This Django view escapes the entire value as HTML text before returning it.

python
import html

from django.http import HttpResponse

def preview(request):
    value = request.GET.get("value", "")
    return HttpResponse(html.escape(value, quote=True))

Usage considerations

When displaying stored values, check where each value goes in the template or DOM every time you render it.

References