Jump to solution
Verify

The Fix

Upgrade to version 0.24.0 or later.

Based on closed Kludex/starlette issue #472 · PR/commit linked

Production note: Most teams hit this during upgrades or environment changes. Roll out with a canary and smoke critical endpoints (health, OpenAPI/docs) before 100%.

Jump to Verify Open PR/Commit
@@ -2,8 +2,9 @@ import anyio +from starlette.background import BackgroundTask from starlette.requests import Request -from starlette.responses import Response, StreamingResponse
repro.py
from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.middleware.base import BaseHTTPMiddleware from starlette.routing import Mount, Route from starlette.staticfiles import StaticFiles from starlette.templating import Jinja2Templates from starlette.testclient import TestClient templates = Jinja2Templates(directory="templates") async def homepage(request): return templates.TemplateResponse("index.html", {"request": request}) routes = [ Route("/", endpoint=homepage), Mount("/static", StaticFiles(directory="static"), name="static"), ] class CustomMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): response = await call_next(request) return response app = Starlette(debug=True, routes=routes, middleware=[Middleware(CustomMiddleware)]) def test_homepage(): client = TestClient(app) response = client.get("/") assert response.status_code == 200 assert response.template.name == "index.html" assert "request" in response.context
verify
Re-run the minimal reproduction on your broken version, then apply the fix and re-run.
fix.md
Option A — Upgrade to fixed release\nUpgrade to version 0.24.0 or later.\nWhen NOT to use: This fix should not be used if the application relies on specific middleware behavior.\n\nOption C — Workaround\nused in https://github.com/atviriduomenys/spinta/pull/22 but I'd rather not override such an important piece\nWhen NOT to use: This fix should not be used if the application relies on specific middleware behavior.\n\n

Why This Fix Works in Production

  • Trigger: E AssertionError
  • Mechanism: The AssertionError occurs due to the middleware not handling the response type correctly
  • Why the fix works: Implements the Debug extension to resolve the AssertionError encountered with middleware and TemplateResponse in tests. (first fixed release: 0.24.0).
Production impact:
  • If left unfixed, the same config can fail only in production (env differences), causing startup failures or partial feature outages.

Why This Breaks in Prod

  • Shows up under Python 3.7 in real deployments (not just unit tests).
  • The AssertionError occurs due to the middleware not handling the response type correctly
  • Surfaces as: tests/test_templates.py:29: in test_templates

Proof / Evidence

  • GitHub issue: #472
  • Fix PR: https://github.com/kludex/starlette/pull/1991
  • First fixed release: 0.24.0
  • Reproduced locally: No (not executed)
  • Last verified: 2026-02-09
  • Confidence: 0.85
  • Did this fix it?: Yes (upstream fix exists)
  • Own content ratio: 0.33

Discussion

High-signal excerpts from the issue thread (symptoms, repros, edge-cases).

“The Debug extension was merged on asgiref. :pray:”
@Kludex · 2022-12-30 · confirmation · source
“A slightly neater solution, which can be injected into any test which already has the client injected: Keeping my fingers crossed that this problem gets…”
@fgimian · 2020-10-06 · source
“btw: I think in general more verbose asserts should be used, e.g. in this case: > assert message["type"] == "http.response.start", message or > assert message["type"]…”
@blueyed · 2019-04-09 · source
“Here's my hacky workaround to this for now in case it helps anyone: I then inject client_without_middleware into tests which render Jinja2 templates.”
@fgimian · 2020-09-15 · source

Failure Signature (Search String)

  • E AssertionError

Error Message

Stack trace
error.txt
Error Message ------------- tests/test_templates.py:29: in test_templates response = client.get("/") .venv/lib/python3.7/site-packages/requests/sessions.py:546: in get return self.request('GET', url, **kwargs) starlette/testclient.py:421: in request json=json, .venv/lib/python3.7/site-packages/requests/sessions.py:533: in request resp = self.send(prep, **send_kwargs) .venv/lib/python3.7/site-packages/requests/sessions.py:646: in send r = adapter.send(request, **kwargs) starlette/testclient.py:238: in send raise exc from None starlette/testclient.py:235: in send loop.run_until_complete(self.app(scope, receive, send)) /usr/lib/python3.7/asyncio/base_events.py:584: in run_until_complete return future.result() starlette/applications.py:134: in __call__ await self.error_middleware(scope, receive, send) starlette/middleware/errors.py:122: in __call__ raise exc from None starlette/middleware/errors.py:100: in __call__ await self.app(scope, receive, _send) starlette/middleware/base.py:25: in __call__ response = await self.dispatch_func(request, self.call_next) tests/test_templates.py:21: in noop response = await call_next(request) starlette/middleware/base.py:47: in call_next assert message["type"] == "http.response.start" E AssertionError

Minimal Reproduction

repro.py
from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.middleware.base import BaseHTTPMiddleware from starlette.routing import Mount, Route from starlette.staticfiles import StaticFiles from starlette.templating import Jinja2Templates from starlette.testclient import TestClient templates = Jinja2Templates(directory="templates") async def homepage(request): return templates.TemplateResponse("index.html", {"request": request}) routes = [ Route("/", endpoint=homepage), Mount("/static", StaticFiles(directory="static"), name="static"), ] class CustomMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): response = await call_next(request) return response app = Starlette(debug=True, routes=routes, middleware=[Middleware(CustomMiddleware)]) def test_homepage(): client = TestClient(app) response = client.get("/") assert response.status_code == 200 assert response.template.name == "index.html" assert "request" in response.context

Environment

  • Python: 3.7

What Broke

Tests fail with AssertionError when using middleware with TemplateResponse.

Why It Broke

The AssertionError occurs due to the middleware not handling the response type correctly

Fix Options (Details)

Option A — Upgrade to fixed release Safe default (recommended)

Upgrade to version 0.24.0 or later.

When NOT to use: This fix should not be used if the application relies on specific middleware behavior.

Use when you can deploy the upstream fix. It is usually lower-risk than long-lived workarounds.

Option C — Workaround Temporary workaround

used in https://github.com/atviriduomenys/spinta/pull/22 but I'd rather not override such an important piece

When NOT to use: This fix should not be used if the application relies on specific middleware behavior.

Use only if you cannot change versions today. Treat this as a stopgap and remove once upgraded.

Fix reference: https://github.com/kludex/starlette/pull/1991

First fixed release: 0.24.0

Last verified: 2026-02-09. Validate in your environment.

Get updates

We publish verified fixes weekly. No spam.

Subscribe

When NOT to Use This Fix

  • This fix should not be used if the application relies on specific middleware behavior.

Verify Fix

verify
Re-run the minimal reproduction on your broken version, then apply the fix and re-run.

Did This Fix Work in Your Case?

Quick signal helps us prioritize which fixes to verify and improve.

Prevention

  • Add a stress test that runs high-concurrency workloads and fails on thread dumps / blocked locks.
  • Enable watchdog dumps in prod (faulthandler, thread dump endpoint) to capture deadlocks quickly.

Version Compatibility Table

VersionStatus
0.24.0 Fixed

Related Issues

No related fixes found.

Sources

We don’t republish the full GitHub discussion text. Use the links above for context.