- Back end is developed using python Fast APIs and running on http://127.0.0.1:9000.
- 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.