Skip to content

How to Fix Python Starlette Middleware Error

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about How to Fix Python Starlette Middleware Error. We cover key concepts, practical examples, and best practices.

Starlette middleware fails when the ASGI scope is modified incorrectly, the response is returned without awaiting, or the middleware order causes unexpected behavior.

The Wrong Way

from starlette.applications import Starlette
from starlette.responses import JSONResponse

class BrokenMiddleware:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        await self.app(scope, receive, send)
        response = JSONResponse({"modified": True})
        await response(scope, receive, send)

app = Starlette()
app.add_middleware(BrokenMiddleware)

Output:

RuntimeError: ASGI 'send' called twice.

The Right Way

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware

class WorkingMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        response = await call_next(request)
        response.headers["X-Modified"] = "true"
        return response

app = Starlette()
app.add_middleware(WorkingMiddleware)

@app.route("/")
async def homepage(request):
    return JSONResponse({"hello": "world"})

All responses now include the X-Modified header.

Prevention Tips

  • Use BaseHTTPMiddleware for request/response middleware.
  • Never call send() directly unless you are writing raw ASGI middleware.
  • Always await call_next(request) before modifying the response.
  • Use Middleware class from Starlette for lower-level control.
  • Register middleware in the correct order.

Common Mistakes with starlette middleware

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. Non-exhaustive pattern matches that compile with warnings then crash at runtime

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the difference between BaseHTTPMiddleware and raw ASGI middleware?

BaseHTTPMiddleware provides a request/response abstraction. Raw ASGI middleware operates on the ASGI scope, receive, and send protocol. Use BaseHTTPMiddleware for most cases and raw ASGI for streaming or protocol-level modifications.

Can I add middleware after routes are defined?

Yes, app.add_middleware() can be called anytime before the first request. Middleware wraps the existing app stack. Middleware registered last wraps the outermost layer.

How do I exclude certain paths from Starlette middleware?

Override the dispatch method in your middleware class. Check request.url.path and return await call_next(request) immediately for paths that should be excluded.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro