Exercise 1: A CORS-Header Middleware — Possible Solution ==================================================================== THE MIDDLEWARE ------------------------------ def cors_middleware(request, next): response = next(request) response.headers["Access-Control-Allow-Origin"] = "*" return response This follows the exact same "after next() returns" shape as the chapter's own timing_middleware -- the header is set on the real Response object only once the handler (and everything nested inside it) has already finished producing it. TESTING IT ------------------------------ def handler1(request): return Response("hello") app1 = build_chain([cors_middleware], handler1) result1 = app1({"path": "/"}) print(result1.body) # hello print(result1.headers) # {'Access-Control-Allow-Origin': '*'} RESULT, VERIFIED DIRECTLY ------------------------------ body: hello headers: {'Access-Control-Allow-Origin': '*'} The real Response object returned by the whole chain carries both the handler's own real body ("hello") and the header the middleware added afterward, confirming the middleware genuinely modified the same object the handler produced rather than creating a separate one. WHY THIS WORKS AS AN ANSWER ---------------------------- It follows the chapter's own established "run code after next() returns, then modify the response before handing it back" pattern exactly, and verifies the result against a real Response object's own headers dict rather than only asserting the header would be present.