I have an MERN app with a front end deployed on onrender.com and backend deployed on onrender.com.
I am attempting to use cookies and jwt for authentication but am having a lot of trouble with cookies being persistent. For example, I would log in, and be directed to my login backend route through axios with the following:
axios.post("https://backend.onrender.com/login", { username, password }, { withCredentials: true })
My backend route for login is the following:
app.post('/login', async (req, res) => {
console.log("Trying to login...");
const { username, password } = req.body;
const user = await Users.findOne({ email: username });
if (user && bcrypt.compareSync(password, user.password)) {
console.log('Logged in');
const token = jwt.sign({ id: user._id, admin: user.role }, SECRET_KEY, { expiresIn: '3h' });
const expirationDate = new Date();
expirationDate.setTime(expirationDate.getTime() + (2 * 60 * 60 * 1000)); // 2 hours expiration
res.cookie('token', token, {
path: "/",
sameSite: 'none',
secure: true,
expires: expirationDate,
});
res.send({ success: true, user: username, token: token });
} else {
console.log("Failed to Login");
res.send({ success: false, message: 'Invalid Input: Incorrect Email/Password!' });
}
});
This is my cors settings:
app.use(cors({
origin: ["https://frontend.onrender.com", "http://localhost:3000"],
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
}));
The cookie gets set but I also get this warning in my cookies tab in dev tools:
Warning for Cookie
I’m pretty confused as to why this is happening so any help would mean a lot!
I have tried on local host and it seems to work fine.
Brice Joseph is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.