[Python] Unable to set two cookies in response header

Discussão em 'Python' iniciado por Stack, Setembro 12, 2025.

  1. Stack

    Stack Membro Participativo

    My FastAPI endpoint looks like this:

    @router.post("/test-cookies")
    async def test_cookies(request: Request, response: Response):
    try:
    response.set_cookie(
    key="access_token",
    value="access_token", # Use f"Bearer {real_token}" in prod
    httponly=False,
    secure=False, # Set to True only for HTTPS
    samesite="lax",
    max_age=(settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60),
    path="/",
    domain=None, # Optional: Helps with localhost subdomains
    )

    # Separate cookie for refresh token
    response.set_cookie(
    key="refresh_token",
    value="refresh_token", # Use real refresh token
    httponly=False,
    secure=False, # Set to True only for HTTPS
    samesite="lax",
    max_age=(settings.REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60 * 60),
    path="/", # Changed to "/" for easier testing
    domain=None, # Optional
    )

    except Exception as e:
    print(f"Error in endpoint: {e}") # Log the issue
    raise # Re-raise for FastAPI error response
    # Separate cookie for access token

    return {
    "message": "Cookies set successfully",
    "debug": "Check browser dev tools or Postman cookies tab",
    }



    Only the first cookie that gets set is coming back in the response. I tested this in Postman. That means the refresh token cookie isn’t being set. I have no idea what to do next, and my middleware isn’t changing the headers either. I'm using uvicorn.

    Please help.

    FastAPI version -> 0.116.1 Starlette version -> 0.37.2

    Continue reading...

Compartilhe esta Página