How to manage Cookies in Magento 2

Mai Xuan Truong

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 quickly get those data. It’s really convenient. In this blog, I would like to introduce you to a detailed guide on how to manage cookies 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:

<?xml version="1.0"?>

<config xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Magenest_CookieDemo" setup_version="1.1.3">
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>
</config>

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

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Magenest_CookieDemo',
    __DIR__
);

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

<?xml version="1.0"?>

<config xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
    <router id="standard">
        <route id="cookie" frontName="cookie">
            <module name="Magenest_CookieDemo"/>
        </route>
    </router>
</config>

The preparation is done, now let’s move on to 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 based 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:
<?php
namespace Magenest\CookieDemo\Controller\Cookie;

use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Action\Action;
use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory;
use Magento\Framework\Stdlib\CookieManagerInterface;

/**
 * Class SetCookie
 * @package Magenest\CookieDemo\Controller\Cookie
 */
class SetCookie extends Action
{
    const COOKIE_NAME = 'Magenest_Cookie';
    const COOKIE_DURATION = 86400; // One day (86400 seconds)

    /**
     * @var CookieManagerInterface
     */
    protected $cookieManager;

    /**
     * @var CookieMetadataFactory
     */
    protected $cookieMetadataFactory;

    /**
     * @param Context $context
     * @param CookieManagerInterface $cookieManager
     * @param CookieMetadataFactory $cookieMetadataFactory
     */
    public function __construct(
        Context $context,
        CookieManagerInterface $cookieManager,
        CookieMetadataFactory $cookieMetadataFactory
    )
    {
        $this->cookieManager = $cookieManager;
        $this->cookieMetadataFactory = $cookieMetadataFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $metadata = $this->cookieMetadataFactory
            ->createPublicCookieMetadata()
            ->setDuration(self::COOKIE_DURATION);
        $this->cookieManager
            ->setPublicCookie(self::COOKIE_NAME, 'Value which you want to save in cookie', $metadata);
        echo "Your value was saved in Cookie!";
    }
}
  • To get Cookie data, create GetCookie.php with the below content:
<?php
namespace Magenest\CookieDemo\Controller\Cookie;

use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Action\Action;
use Magento\Framework\Stdlib\CookieManagerInterface;

/**
 * Class GetCookie
 * @package Magenest\CookieDemo\Controller\Cookie
 */
class GetCookie extends Action
{
    /**
     * @var CookieManagerInterface
     */
    protected $cookieManager;

    /**
     * GetCookie constructor.
     * @param Context $context
     * @param CookieManagerInterface $cookieManager
     */
    public function __construct(
        Context $context,
        CookieManagerInterface $cookieManager
    )
    {
        $this->cookieManager = $cookieManager;
        parent::__construct($context);
    }

    public function execute()
    {
        $cookieValue = $this->cookieManager->getCookie(SetCookie::COOKIE_NAME);
        echo $cookieValue;
    }
}
  • Apply this snippet to the DeleteCookie.php in order to delete:
<?php
namespace Magenest\CookieDemo\Controller\Cookie;

use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Action\Action;
use Magento\Framework\Stdlib\CookieManagerInterface;

/**
 * Class GetCookie
 * @package Magenest\CookieDemo\Controller\Cookie
 */
class DeleteCookie extends Action
{
    /**
     * @var CookieManagerInterface
     */
    protected $cookieManager;

    /**
     * GetCookie constructor.
     * @param Context $context
     * @param CookieManagerInterface $cookieManager
     */
    public function __construct(
        Context $context,
        CookieManagerInterface $cookieManager
    )
    {
        $this->cookieManager = $cookieManager;
        parent::__construct($context);
    }

    public function execute()
    {
        $this->cookieManager->deleteCookie(SetCookie::COOKIE_NAME);
        echo "Cookie was deleted!";
    }
}

In Conclusion,

Well done, you just completed this module. Let’s open your browser and go to the following Url to check the result:
//localhost/[MAGENTO_ROOT]/cookie/cookie/[actions_you_want_to_do]

Hope you find this article helpful and have fun learning Magento. If you are having difficulty managing cookies in your Magento 2 store, or are interested in our elite Magento development services, don’t hesitate to reach out! At Magenest, we guarantee the highest quality at an unbeatable price.

Latest Insights

How to Start a Shopify Store in Just Over an Hour Course

Don't want to miss out on our latest insights?
Subscribe to our newsletter.

Disclaimer: By clicking submit, you agree to share your information with us to receive news, announcements, and resources when they are available.