Set Javascript Cookie Expires and Max-Age

I’m trying to set a cross browser expiration date for my cookie by setting both the “expires” and “max-age” options.
Please take a look at my code below to see if there is something wrong with the way I set up my cookie and its expiration date.

let names = JSON.stringify(employees);
let expirationDate = new Date();
//expires in 10 years
expirationDate.setTime(expirationDate.getTime() + 3650 * 24* 60 * 60 * 1000);
let expires = "; expires=" + expirationDate.toUTCString();
//expires in 10 years
let maxAge = "; max-age=" + 3650*24*60*60;
document.cookie = "employeeNames=" + names +  maxAge;

I set the cookie to expire in 10 years using both “expires” and “max-age” but when I hover over cookie during debug, it shows the following:

"[{"name":"test1"},{"name":"test2"}]; ai_user = dUFeb8|2019-07-22T20:33:20.533Z"

The questions I have are number one can I use both “expires” and “max-age” on a cookie, number 2 is the expiration date supposed to show as part of the cookie, and number 3 why does it say Feb8|2019-07 if it’s supposed to expire 10 years from now.

at what stage do you actually tell the cookie to expire?

No you don’t.

Yes. Browsers that support max-age will use max-age and ignore expires; IE will ignore max-age and use expires, because IE is a silly, silly thing.

What browser are you viewing the cookie in, and what mechanism are you using to do it? Chrome has a nice cookie display section in its settings that will show you the expiry set for your cookie.

2019-07-22T20:33:20 would be nearly the correct time, depending on when you actually set this cookie; 3650 days is not actually quite 10 years, because you’ve forgotten about leap years, but it’s close enough that people probably won’t notice losing a couple of days from the end of their expiry.

Why don’t you just increase the year of the date by 10 years? That will be much more accurate than the way things are currently being done.

LOL yeah, if you want the cookie to expire in exactly 10 years then you might try the following:

const date = new Date()
date.setFullYear(date.getFullYear() + 10)

… although 10 years are pretty much eternity in internet scales – you might as well have it never expire. ^^

Edit: Whoops x-post – like @Paul_Wilkins said.

though keep in mind max age isnt taking a date, it takes a number of seconds, and then the browser internally applies that number to current timestamp to arrive at expiry.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.