How to delete cookies in Magento 2

How to Delete Cookies in Magento 2?

In Magento 2, cookies are deleted using Magento\Framework\Stdlib\CookieManagerInterface interface class.

A cookie is deleted using the deleteCookie() function from CookieManagerInterface Interface Class in Magento 2

If you have set the cookie using the cookie’s $metadata property, You need to inject Magento\Framework\Stdlib\Cookie\CookieMetadataFactory factory in the constructor of your class to delete the cookie. Now, let’s check how to delete cookies in Magento 2 using a Model class. You can use it in Controller, Block, or Helper class as per your need.

Create a Model class to delete cookies in Magento 2:

<?php

namespace Vendor\Module\Model;

class Cookie
{
    /**
    * @var \Magento\Framework\Stdlib\CookieManagerInterface CookieManagerInterface
    */
    private $cookieManager;

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

    public function __construct(
        \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager,
        \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory
    ) {
        $this->cookieManager = $cookieManager;
        $this->cookieMetadataFactory = $cookieMetadataFactory;
    }

    /** Delete the Custom Cookie */
    public function deleteCookie()
    {
        if ($this->cookieManager->getCookie('custom-shop-session-cookie')) {
            $metadata = $this->cookieMetadataFactory->createPublicCookieMetadata();
            $metadata->setPath('/');
            return $this->cookieManager->deleteCookie('custom-shop-session',$metadata);
        }
    }
}

You can replace ‘custom-shop-session-cookie’ with the name of the cookie you want to delete.

You can also use the following code to delete all the cookies:

$cookieManager = $objectManager->get(\Magento\Framework\Stdlib\CookieManagerInterface::class);
$cookieManager->getCookie('*', '/');

Note that this code assumes that you have an instance of the object manager, typically done by injecting it into the constructor of your class.

This will delete all cookies for the entire domain.

I hope this helps! If you have any further questions, please don’t hesitate to reach out.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments