I'm working on a mern stack project with next.js framework. I hold the jwt token with a cookie and perform its verification directly over the backend. I use a useEffect on the index page to logout when the cookie expires. If there is no cookie, it needs to logout. When I was in the development phase (on localhost) everything was working flawlessly. But when I take the project live, it doesn't work. I am using vercel for the frontend server and aws ec2 for the backend server.
index.js - logout useEffect
useEffect(() => {
console.log(getCookie('acces_token'));
if (getCookie("access_token") === undefined) {
logOut(dispatch);
}
}, [])
Express google login controller
const googleAuth = async (req, res, next) => {
try {
const user = await User.findOne({ email: req.body.email });
if (user) {
const token = jwt.sign({ id: user._id }, process.env.SECRET_KEY, { expiresIn: "5d" });
res.cookie("access_token", token, {
secure: true,
sameSite: "none",
expires: new Date(Date.now() + (30 * 24 * 3600000))
})
res.status(200).json(user._doc)
} else {
const newUser = new User({
...req.body
})
const savedUser = await newUser.save();
const token = jwt.sign({ id: savedUser._id }, process.env.SECRET_KEY, { expiresIn: "5d" });
res.cookie("access_token", token, {
secure: true,
sameSite: "none",
expires: new Date(Date.now() + (30 * 24 * 3600000))
})
res.status(200).json(savedUser._doc)
}
} catch (err) {
console.log(err)
}
}
The main problem is that I can provide cookie access through localhost. I can also see cookie when site is live. The problem is that when he tries to read, he just throws undefined. Although there is data inside.
I solved this problem later with cookie domain. In the Domain section write like this ".yourdomain.com" on when set cookies, it will accept all domain-linked cookies.