microcipcip / cookie-universal

Universal cookie plugin, perfect for SSR
526 stars 39 forks source link

option expires in invalid #51

Closed mortezasabihi closed 4 years ago

mortezasabihi commented 4 years ago

when i use expiration in my code:

 this.$cookies.set('cookie-consent', this.cookieConsent, {  expires: new Date().getFullYear() + 1 })

i get this error message:

option expires in invalid
microcipcip commented 4 years ago

Hi @mortezasabihi, the reason that you are unable to set it is that expires according to both this library documentation and MDN documentation, has to be a proper date object. When you sum new Date() with 1, you are transforming from date to number. A proper date to pass would be something like this Thu, 01 Jan 2019 00:00:00 GMT. I usually don't use expires as I find maxAge easier to use as there I can easily set a number instead (in seconds), for example: maxAge: 60*60*24 would make the cookie expire in 1 day.

Hope this helps you fix your problem.

microcipcip commented 4 years ago

You can of course set expires with the help of a library like date-fns or with a function like this:

const addYears = (date, yearsToAdd = 1) => {
  const newYear= date.getFullYear() + yearsToAdd
  const newDate = new Date(date.setFullYear(newYear))
  return newDate ;
}

 this.$cookies.set('cookie-consent', this.cookieConsent, {  expires: addYears(new Date(), 1) })