How to Use Magento 2 Cookies

How to Use Magento 2 Cookies

In Magento 2 and many other eCommerce platforms, cookies play a vital role in handling data across sessions. They are small text files stored on the client’s browser, designed to retain various types of information, such as session state, user preferences, shopping cart data, and more. Magento 2 Cookies allow store owners to maintain a seamless user experience as customers navigate through the store or return later. This article explores how cookies function and how to effectively use them within Magento 2.

To set a cookie in Magento 2, use the setPublicCookie method with a duration, name, and value. This allows you to store user preferences or session details. Retrieve the value of a cookie using the getCookie method, which retrieves stored session data by name. To maintain security or user privacy, use the deleteCookie function to remove the specified cookie. By implementing best practices for secure cookie handling, regulatory compliance, and performance optimization, you can maximize the benefits of cookies in Magento 2.

Types of Magento 2 Cookies

Session Cookies:

  • These are temporary cookies that last for the duration of the session and are deleted when the browser is closed.
  • They manage actions like adding items to a cart or keeping users logged in during the session.

Persistent Cookies:

  • These remain on the user’s browser until they expire or are manually deleted.
  • They store long-term data, such as user preferences, to ensure a personalized experience on return visits.

Secure Cookies:

  • Sent only over HTTPS connections, secure cookies protect sensitive data, such as authentication tokens.

Third-party Cookies:

  • External services (such as analytics or advertising platforms) use these cookies to track user behavior across different websites.

Setting Cookies in Magento 2

To set a cookie, we use the setPublicCookie method with a duration, name, and value. This cookie can store user preferences or session details.

   /**
     * create custom cookie
     */
    public function setCookie($name, $value, $duration = 86400){
        $metadata = $this->cookieMetadataFactory
            ->createPublicCookieMetadata()
            ->setSecure(false)
            ->setHttpOnly(false)
            ->setDuration($duration);
        $this->cookieManager->setPublicCookie(
            $name,
            $value,
            $metadata
        );
    }

Getting Cookies in Magento 2

The getCookie method retrieves the value of a cookie by name, allowing you to access stored session data.

/**
  * read/get custom cookie by name
  */
  public function getCookie($name){
    return $this->cookieManager->getCookie($name);
  }

Deleting Cookies in Magento 2

The rdeleteCookie function removes the specified cookie, which is essential for maintaining security or user privacy

/**
  * remove/delete custom cookie by name
  */
  public function deleteCookie($name){
    $this->cookieManager->deleteCookie($name);
  }

complete code

<?php

declare(strict_types=1);

namespace Vendor\Module\Helper;

use Magento\Framework\App\Helper\AbstractHelper;

class ManageCookie extends AbstractHelper
{
    /**
    * @var \Magento\Framework\Stdlib\CookieManagerInterface
    */
    protected $cookieManager;

    /**
    * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
    */
    protected $cookieMetadataFactory;

    /**
     * @param \Magento\Framework\App\Helper\Context $context
     */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager,
        \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory
    ) {
        parent::__construct($context);
        $this->cookieManager = $cookieManager;
        $this->cookieMetadataFactory = $cookieMetadataFactory;
    }

    /**
     * create custom cookie
     */
    public function setCookie($name, $value, $duration = 86400){
        $metadata = $this->cookieMetadataFactory
            ->createPublicCookieMetadata()
            ->setSecure(false)
            ->setHttpOnly(false)
            ->setDuration($duration);
        $this->_cookieManager->setPublicCookie(
            $name,
            $value,
            $metadata
        );
    }

    /**
     * read/get custom cookie by name
     */
    public function getCookie($name){
        return $this->cookieManager->getCookie($name);
    }

    /**
     * remove/delete custom cookie by name
     */
    public function deleteCookie($name){
        $this->_cookieManager->deleteCookie($name);
    }
}

Magento 2 Cookies are essential for creating a smooth and personalized shopping experience. By managing sessions, retaining user preferences, and ensuring security, cookies help enhance both user engagement and website functionality. Adopting best practices like secure cookie handling, ensuring regulatory compliance, and optimizing performance will help you make the most of cookies in Magento 2.

Leave a Reply

Your email address will not be published. Required fields are marked *