Reading cookie expiration date

JavascriptHtmlXhtmlCookies

Javascript Problem Overview


Is it possible to read cookie expiration date using JavaScript?

If yes, how? If not, is there a source I can look at?

Javascript Solutions


Solution 1 - Javascript

It is not possible to get the expiration date of a cookie through Javascript; only key-value pairs are exposed through document.cookie.

Solution 2 - Javascript

If you are using Chrome you can goto the "Application" tab (within Developer Tools) and find the item "Cookies" in the left sidebar. From there select the domain you are checking the set cookie for and it will give you a list of cookies associated with that domain, along with their expiration date.

Solution 3 - Javascript

There are some who will find this contentious - but one solution is to create another cookie at the same time and store the time/stamp in it parallel with whichever original cookie is created. Update them both at the same time and that way you can easily get the time from your new cookie (Alternatively append the time/stamp in your source cookie).

The reason this would be contentious is that over the years the idea of storing cookies on a users PC isn't popular because you are taking up their space. However I really doubt a small timestamp cookie would be too horrific.

Its worth remembering that if a time has passed then the browser will not report that cookie available. The browser may show the cookie present but when JS tries to access it - it won't be able too.

Additionally I found that WebDeveloper toolbar in Firefox shows cookies that have passed but under Firefox > Privacy settings they are updated correctly.

Solution 4 - Javascript

If you have control over the code where the cookie is set, then you can add code to store the expiration date in the browser's local storage for later retrival. For example:

// set cookie with key and value to expire 30 days from now
var expires = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
document.cookie = [
	"key=value",
	"expires=" + expires.toUTCString()
].join("; ");

// store cookie expiration date for key in local storage
if (window.localStorage) {
	localStorage.setItem("keyExpires", expires.toISOString());
}

Later, you can lookup when the cookie expires in local storage. For example:

var expires = localStorage.getItem("keyExpires");

Local storage currently has broad support.

https://caniuse.com/#feat=namevalue-storage

Solution 5 - Javascript

I agree with @Daniel, as he answered this in 2009.

But right now, I came across a similar problem and I found a better way to read the expiry date of cookie in Javascript.

The CookieStore type of the cookies API represents a cookie store in the browser.

YOU CAN NOT USE THIS FOR NON HTTPS SITES

This is compatible with all modern browsers.

All you need is to

// list of all the cookies
cookieStore.getAll().then(cookies=>console.log(cookies))

// returns object of the single cookie by NAME   
cookieStore.get('NAME_OF_THE_COOKIE').then(cookies=>console.log(cookies))

The output of CookieStore will be Promise, so you will need to resolve it. after that result array of cookies in the following format.

domain: null
expires: 1615699665000 //TIMESTAMP
name: "STR"
path: "/"
sameSite: "STR"
secure: "BOOL"
value: "STR"

Please feel free to correct me or update my answer for the better help of others.

Solution 6 - Javascript

You have several options.

  1. Save expire timestamp somewhere else - e.g. localStorage or another Cookie
  2. In Chrome and Edge - use CookieStore API which i describe below

You can use CookieStore API which is "experimental" as I write, yet it's supported by Chrome. Can't test, but seems like on Edge too. Tested on Safari, it's undefined, so not supported.

Yet you can check here: https://caniuse.com/?search=CookieStore
Read more here: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies/CookieStore

On Chrome sample response:

enter image description here

Safari 15.1 (2021-11-13):

enter image description here

Solution 7 - Javascript

Another way to do this would be to write the expiration date into the body of the cookie and then reread it from there for subsequent rewrites. I've gotten this to work with the fantastic js-cookies library.

Setting looks like this:

// Set cookie expiration as a number (of days)
var paywallDuration = 30;

// When you set the cookie, add the `expires` key/value pair for browsers
// Also add `expirationDate` key/value pair into JSON object
Cookies.set('article-tracker', {
  expirationDate : paywallDuration,
  totalArticlesRead: 1
}, {
  expires : paywallDuration,
  domain : 'example.com'
});

Reading your cookie and rewriting is straight-forward with this method. Use js-cookie's getJSON() method to read the expiration date you set. Then, use that date twice when you rewrite your cookie - again in the JSON object and then for the browser with expires:

var existingPaywallDuration = Cookies.getJSON('article-tracker').expirationDate;

Cookies.set('article-tracker', {
  expirationDate: existingPaywallDuration,
  totalArticlesRead: 4
}, {
  expires : existingPaywallDuration,
  domain : 'example.com'
});

Solution 8 - Javascript

There is a work-around to OP's question if you also control the setting of the cookies. I do it like this:

function setCookie(name, value, expiryInDays) {
  const d = new Date();
  d.setTime(d.getTime() + expiryInDays * 24 * 60 * 60 * 1000);

  document.cookie = `${name}=${value}_${d.toUTCString()};expires=${d.toUTCString()}`;
}

function showCookies() {
  if (document.cookie.length !== 0) {
    const allCookies = document.cookie.split(/;\s*/);
    const wrapper = document.getElementById('allCookies');

    wrapper.innerHTML = allCookies.reduce((html, cookie, index) => {
      const cookieParts = cookie.split('=');
      const cookieValueParts = cookieParts[1].split('_');
      const cookieHtml = [
        `<b>${index + 1}</b>`,
        `Cookie name: ${cookieParts[0]}`,
        `Cookie value: ${cookieValueParts[0]}`,
        `Expires: ${cookieValueParts[1] || 'unknown'}`
      ].join('<br>');
      return html + `<p>${cookieHtml}</p>`;
    }, '');
  }
}

<button onclick="showCookies()">Show me the cookies!</button>
<div id="allCookies"></div>

Solution 9 - Javascript

So if the intention of getting the Expires/ Max Age data is to check if the cookie has not expired, to then do some A OR B action.

You could simply check if the cookie is available as the cookies get removed after the expiration date. Info from here

so with tha in mind:

const cookie = readCookieFunction('cookieName');
if(cookie) {
  console.log(`cookie value: ${cookie}`);
  // Do A
} else {
  console.log('cookie has expired');
  // Do B
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDarthVaderView Question on Stackoverflow
Solution 1 - JavascriptDaniel VandersluisView Answer on Stackoverflow
Solution 2 - Javascriptskribbz14View Answer on Stackoverflow
Solution 3 - JavascriptAntonyView Answer on Stackoverflow
Solution 4 - JavascriptKeith ShawView Answer on Stackoverflow
Solution 5 - JavascriptGautam JhaView Answer on Stackoverflow
Solution 6 - JavascriptLukas LiesisView Answer on Stackoverflow
Solution 7 - JavascriptserraosaysView Answer on Stackoverflow
Solution 8 - JavascriptDennis MundingView Answer on Stackoverflow
Solution 9 - JavascriptT04435View Answer on Stackoverflow