i have an issue when trying to send the cookies from browser to nextJs server first let me describe the issue :
- my backend API is built with Nodejs and express, the frontend is handled by Nextjs , when the user try to login the token is stored as an httpOnly cookie ,to get the loggedin user i must send the cookie from my frontend to my backend so i do that through nextJs getServerSideProps function with the help of Context.req.headers.cookie in order to sent this token to my nodeJs backend. this is the login controller (backend):
exports.login = catchAsync(async (req,res,next)=>{
// SOME CODE
const token = jwt.sign({id: user.id}, process.env.JWT_SECRET);
const cookieOption = {
expires: new Date(Date.now() + process.env.JWT_COOKIE_EXPIRES_IN*24*60*60*1000),
httpOnly: true,
secure : true,
sameSite: 'none',
// domain: '.herokuapp.com'
};
res.cookie('jwt', token, cookieOption);
res.status(200).json({
status: 'success',
data: {
user
}
})
});
and this is my getServerSideProps function in which i try to send the token from nextJs to nodeJs server:
export async function getServerSideProps(context){
console.log(context.req.headers.cookie) // EMPTY OBJECT!
console.log(context.req.cookies) //EMPTY OBJECT TOO
let user
try{
const res = await fetch(`${url}/users/isLoggedin`, {
method: 'GET',
credentials:'include',
headers: {
'Access-Control-Allow-Credentials': true,
Cookie: req.headers.cookie
},
})
const data = await res.json()
if(!res.ok){
throw data
}
user = data
}catch(err){
return console.log(err)
}
return {
props: {
user,
}
}
}
i can send the token from browser directly to nodeJs (client side) but i can't send the token from the browser to nextJs server i don't know why, i have tried many solutions but no ones workes for me .
- note: both backend and frontend are deployed to heroku