Double Encoding in FastAPI + Jinja: What It Is and How to Stop It

Double encoding happens when data that is already encoded gets encoded a second time. The browser decodes only once, so users see the leftover encoding instead of the real character. A user types "Tom & Jerry" and the page shows "Tom & Jerry". A file called "my report.pdf" turns into a broken link ending in "my%2520report.pdf".
FastAPI apps that use Jinja run into this a lot. Starlette's Jinja2Templates turns autoescaping on by default for .html files, so Jinja already escapes every {{ variable }}. Escape anything yourself before that and it gets escaped twice.
The Three Kinds You Will Meet
HTML Double Escaping & becomes &, then & becomes &. The page shows raw entities like < where you expected a < character.
URL Double Encoding A space becomes %20, then the % is encoded again, giving %2520. Links break or point to files that don't exist.
JSON Double Encoding json.dumps() runs on data that is already a JSON string. In JavaScript you get a string full of \" escapes instead of an object.
Why It Happens: The Golden Rule
Encode Once, at the Output Boundary Keep data raw (unencoded) in Python, in the database and in your Pydantic models. Encode it only at the moment it leaves for a particular place: HTML, a URL or JSON.
Each Layer Assumes It Is the Only One Jinja doesn't know you already called html.escape(), and url_for doesn't know you already called quote(). Two layers that each mean well produce double encoding.
Case 1: Manual html.escape() Plus Autoescape
The Bug You "help" by escaping in the route, and Jinja escapes the result again.
# main.py (BROKEN)
import html
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/item")
def item(request: Request):
name = html.escape("Tom & Jerry <Classic>") # escape #1
return templates.TemplateResponse(
request, "item.html", {"name": name}
)
<!-- item.html -->
<h1>{{ name }}</h1> <!-- autoescape = escape #2 -->
<!-- Output: Tom &amp; Jerry &lt;Classic&gt; -->
The Fix Pass the raw string and let Jinja do the escaping.
@app.get("/item")
def item(request: Request):
return templates.TemplateResponse(
request, "item.html", {"name": "Tom & Jerry <Classic>"}
)
Case 2: Escaped Data Saved in the Database
The Bug Input gets escaped when it's saved (in a validator, ORM hook or form handler), so every later render escapes it again. Old rows may already be double escaped.
# BROKEN Pydantic validator
from pydantic import BaseModel, field_validator
import html
class Comment(BaseModel):
text: str
@field_validator("text")
@classmethod
def clean(cls, v: str) -> str:
return html.escape(v) # don't do this
The Fix Store raw text and validate length or format, not encoding. To clean up rows that are already corrupted, run a one-time migration with html.unescape(), and test it on a copy before touching production.
class Comment(BaseModel):
text: str # raw; Jinja escapes at render time
Case 3: Trusted HTML That Gets Escaped
The Bug You build HTML in Python (Markdown output, say) and Jinja escapes the tags, so users see as text.
The Wrong Fix Use |safe on everything, or set autoescape=False on the environment. That reopens XSS.
The Right Fix Sanitize first, then mark the result as safe with markupsafe.Markup. Jinja never re-escapes a Markup object.
import markdown, nh3
from markupsafe import Markup
def render_md(raw: str) -> Markup:
html_out = markdown.markdown(raw)
return Markup(nh3.clean(html_out)) # sanitized, then trusted
@app.get("/post")
def post(request: Request):
body = render_md("**Hello** & <script>bad()</script>")
return templates.TemplateResponse(
request, "post.html", {"body": body}
)
<div class="post">{{ body }}</div> <!-- no |safe needed -->
Watch the str() Trap Calling str(Markup(...)), or using an f-string like f"{markup}!", gives back a plain str. Jinja treats a plain str as untrusted and escapes it. Use Markup methods to build the string, e.g. Markup("{}").format(user_value), which escapes only user_value.
Case 4: URL Double Encoding With url_for
The Bug request.url_for() already percent-encodes path parameters. Quote them yourself first and you get %2520.
from urllib.parse import quote
# BROKEN
link = request.url_for("download", filename=quote("my report.pdf"))
# -> /download/my%2520report.pdf
The Fix Pass the raw value to url_for.
link = request.url_for("download", filename="my report.pdf")
# -> /download/my%20report.pdf
<a href="{{ url_for('download', filename=file.name) }}">Get</a>
Query Strings Encode the whole dict once with urlencode(), or use Jinja's |urlencode filter on the raw value. Don't do both.
<a href="/search?q={{ term | urlencode }}">Search</a>
Case 5: JSON Inside Templates
The Bug You call json.dumps() in Python and then |tojson in the template, which wraps the JSON in a second layer of quotes.
# BROKEN
ctx = {"data": json.dumps({"user": "Ana", "role": "admin"})}
<script>
const data = {{ data | tojson }};
// data is a STRING: "{\"user\": \"Ana\", ...}"
</script>
The Fix Pass the Python dict and use |tojson once. It escapes <, >, & and ' as well, which makes it safe inside a script tag.
ctx = {"data": {"user": "Ana", "role": "admin"}}
<script>
const data = {{ data | tojson }}; // real object
</script>
Don't Quote It Writing "{{ data | tojson }}" with quotes around it turns the JSON back into a string, which is double encoding again.
Case 6: The Same Template Rendered Twice
The Bug You render a partial to a string, pass that string into another template, and it gets escaped.
partial = templates.get_template("card.html").render(item=item)
return templates.TemplateResponse(
request, "page.html", {"card": partial} # escaped again
)
The Fix Use {% include "card.html" %} inside page.html. If you really must pre-render, wrap the output as Markup(partial). It's trusted because your own autoescaped template produced it.
Quick Debugging Checklist
Spot the Pattern &, < or %25 in the page source is a clear sign of double encoding.
Search the Codebase grep for html.escape, quote(, json.dumps, |safe and autoescape. Every hit is a possible second layer.
Check the Database Look at raw rows. Any & stored as & means you're escaping at write time.
Trace One Value Follow a single string from the request to the DB, the route context, the template and the browser, and count how many times it gets encoded. The answer should be one.
Summary
One Rule Keep data raw everywhere and encode once, at the edge, for the place it's going.
One Tool per Context Autoescape for HTML, url_for or |urlencode for URLs, |tojson for JavaScript, and Markup only for sanitized, trusted HTML.
Never Disable Autoescape Turning it off fixes the symptom and creates an XSS hole. Remove the extra encoding layer instead.