top of page
Writer's pictureVishesh Dwivedi

Getting null when retrieving customer_id from customer session on product page Magento 2

So as we know, there are two types of content on website - public content and private content. You can go to our blog for reference - https://www.visheshdwivedi.com/post/sections-sections-xml-in-magento-2


Magento 2 uses full page cache to improve storefront. As public content must be cached, Magento 2 caches the product page also. Customer id which we try to retrieve from customer session is private content and it must not be cached. So to prevent private content caching, Magento clears the session storage after the XML generation, look at the following code snippet -


\Magento\Customer\Model\Layout\DepersonalizePlugin.php


public function afterGenerateElements(LayoutInterface $subject)
    {
        if ($this->depersonalizeChecker->checkIfDepersonalize($subject)) {
            $this->visitor->setSkipRequestLogging(true);
            $this->visitor->unsetData();
            $this->session->clearStorage();
            $this->customerSession->clearStorage();
            $this->session->setData(FormKey::FORM_KEY, $this->formKey);
            $this->customerSession->setCustomerGroupId($this->customerGroupId);
            $this->customerSession->setCustomer($this->customerFactory->create()->setGroupId($this->customerGroupId));
        }
    }


This is the reason why we get null value instead of customer id on cached pages.


Magento also requires some private content such as customer group, is customer logged in or not, selected currency, etc. So, Magento uses Context variables to store such type of data and retrieve it whenever needed. We can see such implementation in following classes -

\Magento\Customer\Model\App\Action\ContextPlugin::beforeDispatch , \Magento\Store\App\Action\Plugin\Context::beforeDispatch , etc.


We can also store required information in the context variable and can use it whenever needed. Keep one thing in mind, do not store unique values in the context variable which leads to data overloading, this may result in low cache hit rate.


Thank you. Happy caching :)

31 views0 comments

Recent Posts

See All

Comments


bottom of page