Skip to content

[BUG] Adding BackgroundTask to Redirect results in 200 response. #728

Open

Description

@sergue1

Describe the bug
Adding BackgroundTask to Redirect response results in 200 status code.

Minimal Reproducible Example

app = FastHTML()
cli = TestClient(app, follow_redirects=False)

@app.get("/background")
def background_task():
    def long_running_task():
        time.sleep(0.1)
        print("Background task completed!")
    return Redirect("/"), BackgroundTask(long_running_task)

r = cli.get("/background")
print(r)
print(r.text)

Output:

Background task completed!
<Response [200 OK]>
 <!doctype html>
 <html>
   <head>
     <title>FastHTML page</title>
     <meta charset="utf-8">
...
   <body><fasthtml.core.Redirect object at 0x103863cb0></body>
 </html>

Expected behavior
Expect response. with 303 status code

Environment Information
Please provide the following version information:

  • fastlite version: 0.1.3
  • fastcore version: 1.8.1
  • fasthtml version: 0.12.5

Confirmation
Please confirm the following:

  • I have read the FAQ (https://docs.fastht.ml/explains/faq.html)
  • I have provided a minimal reproducible example
  • I have included the versions of fastlite, fastcore, and fasthtml
  • I understand that this is a volunteer open source project with no commercial support.

Activity

  1. sergue1 commented on May 16, 2025

    @sergue1
    Author

    A workaround I use instead of FastHTML Redirect return Starlette responses:

    def redirect(req: Request, loc: str, background: BackgroundTask | None = None):
        if "hx-request" in req.headers:
            return Response(headers={"HX-Redirect": loc}, background=background)
        else:
            return RedirectResponse(loc, status_code=303, background=background)

    e.g.

    @app.get("/background")
    def background_task(req: Request):
      ...
      return redirect(req, "/", background=long_running_task)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions