Magento2 – How to Set a Mage/Cookies Cookie Expiration Date to the User’s Session

cookiefrontendjavascriptmagento2requirejs

Default jQuery method

In my JS (loaded using Require JS) I'm setting a cookie like so:

$.cookie('hideStickyBanner', 1);

This sets a cookie with the expiration date of session which is exactly what I need.

Magento method

But when I try using the mage/cookies method the expiration date defaults to approx 4 days time.

$.mage.cookies.set('hideStickyBannerMagento', 1);

Question

How can I use the $.mage.cookies.set(); function but have the expiration date be the user's session?

I tried this but the expiration still defaulted to 4 days time:

$.mage.cookies.set('hideStickyBannerMagento', 1, {
    expires: 0
});

Best Answer

$.mage.cookies.set('name', 'value', {lifetime: -1});

Which seems a little crazy, but here's why...

The source for mage/cookies can be found lib/web/mage/cookies.js. The set method, at least in 2.2.0, sets the expires value with this little snippet:

expires = lifetimeToExpires(options, this.defaults) || options.expires;

I don't know why this was done, but is looks backwards to me. The lifetimeToExpires will add the default lifetime to the current time or to options.expires anytime options.lifetime or defaults.lifetime is greater than 0. That means any value passed in options.expires won't be output to the cookie as is.

Setting options.lifetime to any negative number will cause lifetimeToExpires to return null. Later in the set method when the cookie is created no expiration value will be passed and it will default to session.

Related Topic