How to manage Cookie in Magento 2

Cookie is a small piece of data sent from a website and stored on the user’s computer by the user’s web browser while the user is browsing. Then, whenever he is back, he can easily get those data. It’s really convinent, isn’t it?

In this blog, I would like to introduce you a detailed guide about how to manage Cookie in Magento 2.

how to manage cookie in magento 2

Step 1: Setting up Module

In order to manage cookie in Magento 2, we need to create a module. Let’s name it: CookieDemo.

In your Magento root, create the following folders:
_  app/code/Magenest
_  app/code/Magenest/CookieDemo
_  app/code/Magenest/CookieDemo/etc

In the etc folder of the module, create a file called module.xml with the following content:

Next, register the module by creating registration.php file in the app/code/Magenest/CookieDemo/ folder with the following content:

Then, in the etc/frontend folder of the module, create a file called routes.xml:

The preparation is done, now let’s move on Step 2.

Step 2: Managing Cookie by Controller

Firstly, In your Magento root, create the following folder: app/code/Magenest/CookieDemo/Controller

Now we will create controllers base on what we want to do with the Cookie:

  • If you want to save your Cookie, in the Controller folder, create an action file called SetCookie.php contains:

  • To get Cookie data, create GetCookie.php with the below content:

  • Apply this snippet to the DeleteCookie.php in order to delete:


Well done, you just completed this module. Let’s open your browser and go to the following Url to check the result:

Hope you find this article helpful and have fun learning Magento.






Comments (1)

  1. Add custom link in header in Magento 2 | Run your e-commerce store with ease!
    […] Before we begin, if you don’t know how to create a simple custom module in Magento 2, please follow the Step 1 in our guide here : […]

Speak Your Mind

− 3 = 5