Question

I am checking if customer is logged in or not(also i have to display customer name) but sometimes it's not working and after flushing block_html cache it works.

I have tried all possible solutions:-

Tried following but still getting issue:-

Why Customer Session is not working on full page cache?

https://aureatelabs.com/magento-2/how-to-get-customer-session-data-when-a-cache-is-enabled-in-magento-2/

As i R&D and found throgh AJAX technique it can be resolved but not any idea of the same...here are the references:-

https://belvg.com/blog/customer-data-management-in-magento-2.html

https://devdocs.magento.com/guides/v2.3/extension-dev-guide/cache/page-caching/public-content.html#configure-page-variations

So please help me for the same.

Was it helpful?

Solution

Take a look at this

https://github.com/DominicWatts/CustomerLogin

It's the plugin

https://github.com/DominicWatts/CustomerLogin/blob/357bf798252c32517307c2775572c332652f510f/Plugin/Magento/Customer/CustomerData/Customer.php#L43

    $result['is_logged_in'] = $this->customerSession->isLoggedIn();

https://github.com/DominicWatts/CustomerLogin/blob/357bf798252c32517307c2775572c332652f510f/view/frontend/templates/index/index.phtml#L1-L11

<div class="greet welcome" data-bind="scope: 'customer'">
    <!-- ko if: customer().is_logged_in  -->
    <span class="logged-in"
            data-bind="text: new String('<?= $block->escapeHtml(__('Welcome back %1', '%1')) ?>').replace('%1', customer().firstname)">
    </span>
    <!-- /ko -->
    <!-- ko ifnot: customer().is_logged_in  -->
    <span class="not-logged-in"
            data-bind='html:"<?= $block->escapeHtml(__("Please <a href='%1'>login</a>", $block->getUrl('customer/account/login'))) ?>"'>
    </span>
    <!-- /ko -->

Take a look at the how I've used the customer binding and knockout

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top