When User login,app send request to backend / nextjs. Next js set cookies via res.Header(…) and then send respond back to front-end. And there I am not able to get cookies-token, but this token I can see in application/Cookies.
here is backend code
try {
const email = req.body.email
const password = req.body.password
const user = await User.findOne({ email })
if(!user) {
throw new Error(`User doesn't exist!`)
}
// compare password
const validPassword = await bcrypt.compare(password, user.password)
if(!validPassword) {
throw new Error('Invalid password!')
}
const signData = {
userId: user._id,
name: user.name,
email: user.email,
admin: user.isAdmin
}
const token = jwt.sign( signData, process.env.JWT_SECRET, {
expiresIn: '4h',
});
res.setHeader('Set-Cookie', `token=${token}; HttpOnly; Max-Age=${60 * 60 * 24 * 1}; Path=/login`);
return res.status(201).json({
success: true,
message: 'Welcome back',
});
} catch (error) {
console.log(error)
res.status(500).send({
success: false,
message: error.message
})
}
and here is front-end
import Cookies from 'js-cookie';
try {
const res = await axios.post('/api/user/login', data, config)
console.log(res.data)
toast.success(res.data.message)
const token = Cookies.get('token');
console.log('token', token); // token undefined
} catch (error) {
console.log(error)
toast.error(error.response.data.message)
}
}
2
Answers
I think you’ll have to use the cookies() function from next js to read the incoming HTTP res headers.
This only happens in the server component though, but you could just pass it down to a client component
It’s simple. the httponly cookies are not accessible in the client javascript. and that is completely expected. httponly has been created this way to prevent XSS attacks.
Mozilla says: