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:
Similar Reads
How to Set & Retrieve Cookies using JavaScript ? In JavaScript, setting and retrieving the cookies is an important task for assessing small pieces of data on a user's browser. This cookie can be useful for storing user preferences, session information, and many more tasks. Table of Content Using document.cookieUsing js-cookie libraryUsing document
2 min read
How to Get Cookie by Name in JavaScript? Getting a specific name in JavaScript involves parsing the document's cookie string contains all cookies in a single string separated by semicolons and space. The goal is to extract the value of a specific cookie by the name given. The Cookie is defined as a small piece of data that is stored on the
4 min read
How to Set Cookies Session per Visitor in JavaScript? Managing session cookies in JavaScript is essential for web developers to maintain user state and preferences across multiple sessions. The document. cookie property provides a basic mechanism for cookie management, utilizing JavaScript libraries or frameworks can offer enhanced security and flexibi
4 min read
How to Manage Sessions and Cookies in Express JS? Express is a small framework that sits on top of NodeJS web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your applicationâs functionality with middleware and routing. It adds helpful utilities to NodeJS HTTP objects, it helps the rendering of
4 min read
How to list all the cookies of the current page using JavaScript ? Cookies are small pieces of data stored by websites on your browser to remember information about your visit, such as login status, preferences, or other settings. In JavaScript, you can easily retrieve cookies stored by the current domain using document.cookie. However, due to security reasons, you
3 min read