How to set up a cookie that never expires in JavaScript ?
Last Updated :
01 Aug, 2024
We can set up a cookie that never expires in JavaScript using the following approach:
Prerequisites :
- Intermediate level knowledge of JavaScript
- Basic HTML
Disclaimer: 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:
document.cookie = "cookieName= true; expires=Fri, 31 Dec 9999 23:59:59 GMT";
NOTE: But browsers have a problem with the dates after 2038-01-19 04:14:07 as the Unix epoch time exceeds 32-bit int. This problem is also called the Year 2038 problem (also called Y2038, Epochalypse, Y2k38, or Unix Y2K).
Hence, the maximum value you can set as an expiry date for a cookie that is supported by the majority of web browsers is:
231 - 1 = 2147483647 ie. 2038-01-19 04:14:07
Syntax:
document.cookie = "cookieName= true; expires=Tue, 19 Jan 2038 04:14:07 GMT";
// OR
const cookieName = "something";
const cookieValue = "something";
const daysToExpire = new Date(2147483647 * 1000).toUTCString();
document.cookie = cookieName + '=' + cookieValue + '; expires=' + daysToExpire;
Code:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript">
const createCookieWithY2K38 = (cookieName, cookieValue) => {
// Expiry date conversion into UTC standard string
const daysToExpire = new Date(2147483647 * 1000).toUTCString();
// Setting up the cookie name, value with the expiry date
document.cookie =
cookieName + '=' + cookieValue + '; expires=' + daysToExpire;
alert('Welcome ' + cookieValue);
}
const extractUserNameFromCookie = (cookieName) => {
let userName = cookieName + '=';
// Splitting cookie
let allCookieArray = document.cookie.split(';');
for (let i = 0; i < allCookieArray.length; i++) {
// Extracting userName and returning the same
let temp = allCookieArray[i].trim();
if (temp.indexOf(userName) == 0)
return temp.substring(userName.length, temp.length);
}
// Else return empty string
return '';
}
const readCookieAndGreetUser = () => {
let userName = extractUserNameFromCookie('testCookie');
if (userName != '') {
// If user is visiting the page again
// "user" variable will not be a empty string
// returned by the accessCookie() function
// and will greet the user
alert('Welcome ' + userName);
}
else {
userName = prompt('Please enter your name');
if (userName != '' && userName != null) {
createCookieWithY2K38('testCookie', userName);
}
}
}
</script>
</head>
<body onload="readCookieAndGreetUser()"></body>
</html>
Output:
Explore
JavaScript Basics
Array & String
Function & Object
OOP
Asynchronous JavaScript
Exception Handling
DOM
Advanced Topics