This is code in which i am setting the cookie
document.cookie = 'cookie_consent=true; expires=Fri, 31 Dec 9999 23:59:59 GMT Secure';
Below is my code for checking cookie.
useEffect(() => {
const cookieValue = (`; ${document?.cookie}`).split('; cookie_consent=').pop().split(';')[0];
if (!cookieValue) {
console.log("Cookie not avaliable");
}
}, [document?.cookie]);
Cookie is getting expired after accepting within few days since i set cookie expiry as 31 dec 9999 etc.
Thank You in advance, Any help will appreciated.
CodePudding user response:
My assumption would be immediately that 9999 is too great as a year.
See the following post: https://stackoverflow.com/questions/10328361/maximum-lifetime-of-javascript-cookie#:~:text=The max value is 2,on the UNIX timestamp value.
CodePudding user response:
As a side note, set useEffect
with document.cookie
as a dependence will not re-run when document.cookie
change, it only accepts state
dependencies
Also,
All the cookies expire as per the cookie specification. So, there is no block of code you can write in JavaScript to set up a cookie that never expires. It is just impossible and is a fact.
Solution: But you can set up a cookie that expires in JavaScript and pick some very large value as expiry date as specified below:
const expireDate = new Date(2147483647 * 1000).toUTCString();
document.cookie = `cookie_consent=true; expires=${expireDate} Secure`;