Adedara
Adedara

Reputation: 11

Backend (in production - Render) not setting cookies for Frontend in development

My friend and I are working on a project together. I develop the backend with FastAPI and he uses Next.js for the frontend. I implemented session based authorization with session cookies that would be set in the client side and then forwarded to the backend for authorization.

The issue now is, I have deployed the backend (on render), and my friend (somewhere far away) is developing his frontend and he is using the backend URL in production. But we can't even get past the authentication stage because the cookies are not being set. I have tried so many options such as :

But no matter what I do, the cookies still won't get set in the client side. I have no idea what to do and AI doesn't even help as well.

Here is the code below:

@AuthRouter.post("/token", dependencies=[Depends(get_api_key)])
async def login(
    response: Response,
    form_data: password_request_form,
    session: DBSessionDep,
):
    sessionHandler = SessionHandler(session)

    user_login_response = await sessionHandler.login(
        user_matric=form_data.username,
        email=form_data.username,
        password=form_data.password,
    )

    session_token = user_login_response["session_token"]
    response.set_cookie(
        key="session_token",
        value=session_token,
        httponly=True,
        secure=True,  # Set to True for HTTPS
        samesite="None",
        max_age=SESSION_TIMEOUT_MINUTES * 60,
    )

    return user_login_response

I heard something about CORS, and I have set it up already below in my main.py file:

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Just for Development. Would be changed later.
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

What could be wrong?

I tried setting cookies for the frontend from the backend, expecting that the cookie would subsequently be stored and forwarded to the backend on every request. Instead the cookie doesn't ever get saved and authentication cannot even occur.

Upvotes: 1

Views: 30

Answers (0)

Related Questions