Skip to content

Magento 2 Cookie not able to clear from JS

I am unable to clear the cookie on my Magento site.

I am setting the cookie as below which is done successfully

use MagentoFrameworkStdlibCookieCookieMetadataFactory;
use MagentoFrameworkStdlibCookieManagerInterface;


$publicCookieMetadata = $this->cookieMetadataFactory->createPublicCookieMetadata();
$publicCookieMetadata->setPath('/');
$publicCookieMetadata->setHttpOnly(false);
$publicCookieMetadata->setSameSite('Strict');
$this->cookieManager->setPublicCookie(
    self::COOKIE_NAME,
    1,
    $publicCookieMetadata
);

After that, I am reading the cookie in my JS file and then trying to clear it as below:

define([
    'jquery',
    'jquery/ui',
    'Abc_Gtm/js/dataLayerPush',
    'mage/cookies'
], function ($, ui, dlp) {
    'use strict';

    $.widget('gtm.loginSuccess', {
        _create: function () {
            var gtmLogin = $.mage.cookies.get('gtmLoginEventTrigger');
            if(gtmLogin === "1") {
                dlp('event_crm_action','event_profile_login_complete','');
                $.mage.cookies.clear('gtmLoginEventTrigger');
            }
            console.log($.mage.cookies.get('gtmLoginEventTrigger'));
        }
    });
    return $.gtm.loginSuccess;
});

The function of clear cookies is executed successfully but it doesn’t clear the cookie. I also tried setting another value using mage.cookies.set() However, that too isn’t working.

Checked disabling cache and all other solution. Can anyone suggest a better way out?