Today, we will explain you how to manage cookies in JavaScript using the default Mage.Cookie class that comes with Magento.

First, to create a cookie, we are going to use the set method. This function takes three parameters:

  • the first one is the cookie key
  • the second is the value of the cookie
  • finally, the last one is the expiry date

Below, you will find an example:

// Create a 60 days expiry date
var expiryDate = new Date();
expiryDate.setDate(expDate.getDate() + 60);
// Call the set method
Mage.Cookies.set('mycookie', 'yum', expiryDate);

Now that your cookie is set you will have to retrieve it. To do so, the get method takes the cookie key as a parameter.

Mage.Cookies.get("mycookie")

Finally, to erase the cookie, you have to use the set method again and you will delete the cookie by resetting the value and the expiry date to an earlier date.

var eraseDate = new Date();
eraseDate.setTime(eraseDate.getTime()+(-1*24*60*60*1000));
Mage.Cookies.set('mycookie', "", eraseDate);