vasilis 123
vasilis 123

Reputation: 675

unable to set cookie expiration date in javascript

This is my first time using cookies and I want to set an expiration date of 1 day . With my code the cookie is set correctly when I check dev tools but the expires tab says SESSION instead of 1 day from now .

My code :

var createCookie= (title,store,price,pic) =>{
  var product = {
    called:title,
    soldAt:store,
    costs:price,
    image:pic,
  }
  var date = new Date();
  var exp = date.setDate(date.getDate() + 1);
  console.log(exp); //huge number is probably seconds 
  var expires = '; expires='+exp;
  document.cookie =  'prod=' + JSON.stringify(product)+expires+'; path=/'; //added cookie 
}

Upvotes: 3

Views: 2923

Answers (1)

Da Mahdi03
Da Mahdi03

Reputation: 1608

Your date handling is incorrect, your date is returned in the number of seconds and you need a UTC string for cookies expiration dates, so I turned it back into a date object to get its UTC string

var date = new Date();
var expiresDate = new Date(date.setDate(date.getDate() + 1));
var expiresDateString = expiresDate.toUTCString();

In your last line

document.cookie =  'prod=' + JSON.stringify(product)+expires+'; path=/'; //added cookie 

I believe you are missing a semicolon after your product and the word "expires="

try

document.cookie =  `prod=${JSON.stringify(product)}; expires=${expiresDateString}; path=/`; //added cookie

I used a JavaScript template string literal because it allows you to put variables and expressions inside of strings without all the manual concatenations with the "+"s and it helps you not miss characters here and there!

Upvotes: 2

Related Questions