Can't set cookie 'expires' or 'maxAge' in Node.js using Express 3.0
31,571
Solution 1
You have to use req.session.cookie
:
req.session.cookie.expires = false;
req.session.cookie.maxAge = 5 * 60 * 1000;
See also connect docs.
Solution 2
Do note that maxAge is in milliseconds-
res.cookie('jwtToken', token, { maxAge: 2 * 60 * 60 * 1000, httpOnly: true }); // maxAge: 2 hours
Solution 3
The accepted answer doesn't work for me.. but the original question has the version that does work. For example
var language = 'en';
//10 * 365 * 24 * 60 * 60 * 1000 === 315360000000, or 10 years in milliseconds
var expiryDate = new Date(Number(new Date()) + 315360000000);
this.__res.cookie('lang', language, { expires: expiryDate, httpOnly: true });
Author by
Jelle De Loecker
Updated on July 09, 2022Comments
-
Jelle De Loecker almost 2 years
I've been trying to set my cookie's expiry date in Node.js using Express 3.0, but nothing is working.
My first attempt:
res.cookie('user', user, { maxAge: 9000, httpOnly: true });
Just ends in a cookie that has an invalid expiry time according to Chrome. Then I tried to set 'expires' instead, like so:
res.cookie('user', user, { expires: new Date(new Date().getTime()+5*60*1000), httpOnly: true });
And now my cookie is just a session cookie.
Does anyone know how to fix this?
-
Jelle De Loecker about 11 yearsTurns out: it was actually working. Chrome just says the time format is wrong, but it still honours it.
-
lucke84 almost 6 yearsUpvote for the comment on maxAge being in millisecs!
-
Someone Special about 3 yearsprobably the most important answer.
-
robm over 2 yearsI was trying to use a short-lived cookie during development (120s), and got errors about 'Cookie “<cookieName>” has been rejected because it is already expired.' I was actually setting the maxAge to 120ms, which had expired by the time the page loaded. This wasn't easy to find searching, since Express uses ms, but browsers implement RFC 6265 that uses seconds; it's somewhat unexpected that Express does the conversion instead of just passing the value through.
-
olejorgenb almost 2 yearsA strange decision to make it milliseconds considering the standard is seconds.. I'm guessing that decision has cost countless hours.