Not able to set cookies correctly in next js front end app using Fast APIs

  1. Back end is developed using python Fast APIs and running on http://127.0.0.1:9000.
  2. Front end is developed using typescript NextJS framework (v 14.2.3) and running on http://localhost:3000. Opted App Router and app directory. Using axios library to call APIs.

I am trying to set cookies from API in front end app which is running in different domain from back end. The cookies are setting like this in browser ->
Screenshot of browser inspection tools of cookies
Screenshot of browser inspection tools of API call Response headers in network

When I reload the app manually, the cookies are automatically removed from browser. And I am also not able to access these cookies inside the front end NextJS code.

In Back end code:

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
        CORSMiddleware,
        allow_origins=["http://localhost:3000"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
# login API =======================================>>>>>>>>>>>
@router.post("/login", response_model=Token)
async def login_for_access_token(
    response: Response,
    form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
    db: Annotated[AsyncSession, Depends(async_get_db)],
) -> Dict[str, str]:
    user = await authenticate_user(
        username_or_email=form_data.username, password=form_data.password, db=db
    )
    if not user:
        raise UnauthorizedException("Wrong username, email or password.")

    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = await create_access_token(
        data={"sub": user["username"]}, expires_delta=access_token_expires
    )

    refresh_token = await create_refresh_token(data={"sub": user["username"]})
    max_age = settings.REFRESH_TOKEN_EXPIRE_DAYS * 24 * 60 * 60

    response.set_cookie(
        key="refresh_token",
        value=refresh_token,
        httponly=False,
        secure=False,
        samesite="Lax",
        max_age=max_age,
    )
    response.set_cookie(
        key="access_token",
        value=f"Bearer {access_token}",
        httponly=False,
        secure=False,
        samesite="Lax",
        max_age=max_age,
    )

    return {"access_token": access_token, "token_type": "bearer"}

Front end code (calling login API):

import axios from "axios";

const Post = (url: string, requestPayload: any, credentials: boolean = false) => {

    return axios
        .post(url, requestPayload, {
            withCredentials: credentials,
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
        })

}

const HTTP = { Post };

export default HTTP;
const onSubmit: SubmitHandler<UserLoginModelType> = async (data) => {
        toast.remove(); // remove all previous toast messages
        const formData = new URLSearchParams();
        formData.append("username", data.username);
        formData.append("password", data.password);
        HTTP.Post(`http://127.0.0.1:9000/auth/login`, formData, true).then(async (resp) => {
            console.log(resp);
            const responseData = resp.data;
            if (resp) {
                router.push("/dashboard");
                setTimeout(() => {
                    const cookie = Cookies.get("access_token");
                    dispatch(setTokenFromCookie({ access_token: cookie || "" }));
                }, 500)
                toast.custom((t) => (<ToastMessage message="Logged in successfully." t={t} />));
            } else {
                toast.custom((t) => (<ToastMessage toastType="error" message={responseData.detail || "Cannot login."} t={t} />));
            }
        }).catch((error) => {
            console.log("error::::::::", error);
            const errorResp = error.response?.data;
            toast.custom((t) => (<ToastMessage toastType="error" message={errorResp?.detail || error.message} t={t} />));
        })
    }

Trying with this, I wanted to set cookies from back end API in front end. The cookies are setting but I am not able to access cookies inside NextJS application. And also, the cookies are removed when I reload the page.

I changed my back end domain to localhost (url: http://localhost:9000), then the cookies are staying.

My requirement is I want to keep back end and front end in separate domains and set cookies from API to front end and.My requirement is I want to keep back end and front end in separate domains and set cookies from API to front end and also I need to access those cookies inside front end. I need to access those cookies inside front end. And the cookies should stay until explicitly deleted in front end.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật