Skip to content

Set cookies when returning a RedirectResponse #2452

@coltonbh

Description

@coltonbh

Example

from fastapi import FastAPI
from fastapi.responses import Response, RedirectResponse

app = FastAPI()

@app.get("/")
def root():
    return {"Hello": "World"}

@app.get("/cookieset")
def cookie_set(response: Response):
    response.set_cookie(key="works", value="here is your data")
    return "My cookies got set!"

@app.get("/cookiefail")
def cookie_fail(response: Response):
    response.set_cookie(key="works", value="here is your data")
    return RedirectResponse("/")

@app.get("/cookieset2")
def cookie_set2(response: Response):
    # This works, but appears to fall short of what the documentation claims, noted below.
    response.set_cookie(key="works", value="here is your data")
    response.status_code = 307
    response.headers["location"] = "/"
    return response

@app.get("/cookieset3", response_class=RedirectResponse)
def cookie_set3() -> RedirectResponse:
    # Proposed by @mcauto in comments below; sets cookie correctly. Pretty close to "ideal" behavior, I think the best behavior would be /cookieset4
    response = RedirectResponse(url="/")
    response.set_cookie(key="works", value="here is your data", domain="127.0.0.1")
    return response

@app.get("/cookieset4", response_class=RedirectResponse)
def cookie_set4(response: RedirectResponse) -> RedirectResponse:
    response.set_cookie(key="works", value="here is your data", domain="127.0.0.1")
    return response

Description

  • Open the browser and call the endpoint /cookieset.

  • Note the cookie is properly set in localstorage

  • Delete the cookie from local storage.

  • Open the browser and call the endpoint /cookiefail.

  • Note the cookie is NOT set when the response is a redirect response (check local storage for cookies, it is empty)

  • The final /cookieset2 endpoint gives the correct behaviors, but the documentation here appears to suggest that setting cookies on the response argument will be correctly incorporated into the final response.

The solution you would like

I would like cookies to be set when returning a RedirectResponse.

Environment

  • OS: macOS:
  • FastAPI Version 0.62.0:
  • Python version: 3.9.0

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions