[javascript] Javascript Cookie with no expiration date

I would like to set up a cookie that never expires. Would that even be possible?

 document.cookie = "name=value; expires=date; path=path;domain=domain; secure";

I don't want to make the date really large, I am just wondering if there was a value for the expires parameter on the cookie that told it never to expire.

Thanks.

This question is related to javascript cookies

The answer is


Nope. That can't be done. The best 'way' of doing that is just making the expiration date be like 2100.


YOU JUST CAN'T. There's no exact code to use for setting a forever cookie but an old trick will do, like current time + 10 years.

Just a note that any dates beyond January 2038 will doomed you for the cookies (32-bit int) will be deleted instantly. Wish for a miracle that that will be fixed in the near future. For 64-bit int, years around 2110 will be safe. As time goes by, software and hardware will change and may never adapt to older ones (the things we have now) so prepare the now for the future.

See Year 2038 problem


You could possibly set a cookie at an expiration date of a month or something and then reassign the cookie every time the user visits the website again


If you intend to read the data only from the client-side, you can use the local storage. It's deleted only when the browser's cache is cleared.


There is no syntax for what you want. Not setting expires causes the cookie to expire at the end of the session. The only option is to pick some arbitrarily large value. Be aware that some browsers have problems with dates past 2038 (when unix epoch time exceeds a 32-bit int).


You can make a cookie never end by setting it to whatever date plus one more than the current year like this :

var d = new Date();    
document.cookie = "username=John Doe; expires=Thu, 18 Dec " + (d.getFullYear() + 1) + " 12:00:00 UTC";

If you don't set an expiration date the cookie will expire at the end of the user's session. I recommend using the date right before unix epoch time will extend passed a 32-bit integer. To put that in the cookie you would use document.cookie = "randomCookie=true; expires=Tue, 19 Jan 2038 03:14:07 UTC;, assuming that randomCookie is the cookie you are setting and true is it's respective value.


You can do as the example on Mozilla docs:

 document.cookie = "someCookieName=true; expires=Fri, 31 Dec 9999 23:59:59 GMT";

P.S

Of course, there will be an issue if humanity still uses your code on the first minute of year 10000 :)


All cookies expire as per the cookie specification, Maximum value you can set is

 2^31 - 1 = 2147483647 = 2038-01-19 04:14:07

So Maximum cookie life time is

$.cookie('subscripted_24', true, { expires: 2147483647 });