Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set persistent cookie with Express.js

How can I set a cookie that is not removed when the browser is closed?

The docs of res.cookie show option parameters you can pass to the method but I haven't been able to find a configuration that makes the cookie persist after closing the browser.

res.cookie('name', 'spence', { expires: 0 });
like image 748
spencer.sm Avatar asked Oct 16 '25 17:10

spencer.sm


1 Answers

Simply set the expires parameter to some value in the future and the cookie will persist. I was getting hung up in the docs because what I thought I wanted was a "session cookie" but like its name implies, a session cookie only lasts for the duration of the browser session.

While it isn't possible to have a cookie to persist indefinitely, you can essentially do the same thing by setting the cookie to expire on some date far in the future.

var farFuture = new Date(new Date().getTime() + (1000*60*60*24*365*10)); // ~10y
res.cookie('name', 'spence', { expires: farFuture });
like image 174
spencer.sm Avatar answered Oct 18 '25 08:10

spencer.sm