r/FastAPI • u/No-Question-3229 • Jul 20 '24
Question Why Does Setting Cookies Not Work
Im having an issue setting my auth cookies for some reason. I dont know why fast api wont set these cookies.
async def set_cookies():
# Get cookie header
# Used to tell auth server if it should set the login cookies
set_auth_cookies = request.headers.get("set-auth-cookies")
print(f"set-auth-cookies header: {set_auth_cookies}")
print(f"Type: {type(set_auth_cookies)}")
print(f"Boolean value: {bool(set_auth_cookies)}")
if set_auth_cookies != None and bool(set_auth_cookies) == True:
response.set_cookie(key="LIF_USERNAME", value=username, domain=".lifplatforms.com", path="/")
response.set_cookie(key="LIF_TOKEN", value=token, domain=".lifplatforms.com", path="/")
print("set auth cookies")
Ive tried timing to make sure the cookies are being set before the request completes and it looks like thats good. Ive even tried using 'await' on the set cookie functions but complains I cant use await on NoneType. I dont know what else could be causing the issue.
Full Source Code: https://github.com/Lif-Platforms/Lif-Auth-Server/blob/107-make-login-route-set-cookies/src/auth_server.py#L160
3
Upvotes
View all comments
Show parent comment
1
u/Prof-Ro Jul 21 '24
I have a similar question and I'm very new to programming and FastAPI in general. Just started few months back.
My backend is FastAPI on a different domain. And my frontend is react on node on a different domain.
I set the cookie on the FastAPI backend but that is not accessible by the frontend because it's on a different domain. So I ended up moving away from cookies and just passing JWT tokens to the frontend and my frontend stores that token in a cookie for reusing etc.
Is this the right approach for this or should I be doing something different here - like host my frontend and backend on the same domain probably as FastAPI backend with react static files hosted on the FastAPI server itself? Probably that way the cookie set in the backend will be accessible by the frontend files too right?
Thank you in advance, would really appreciate your guidance.