How to manage Cookies in Magento 2

A 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 convenient, isn’t it? In this blog, I would like to introduce you a detailed guide about how to manage cookies in Magento 2.

how to manage cookie in magento 2

Step 1: Setting up Module

In order to manage cookies 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: Manage Cookies in Magento 2 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 cookies:

  • If you want to save your cookies, 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.





Relevant Entries
Attaching PDF file to email on Magento 220170629135407
Create a Widget in Magento 220170426043319
How To Configure Amazon API In Magento 220171002200046