I encountered a strange error while getting customer session in a Controller execute method as below:

$resultPage = $this->_resultPageFactory->create();
$this->_customerSession->isLoggedIn(); // return true;
$this->_customerSession->isLoggedIn(); // return false;

Why the customer session will be cleared at line 4?

  • it's work perfectly. Which version and which mode you use?
    – Sohel Rana
    Aug 9 '16 at 9:36
  • I use v2.0.8 Community Edition
    – Paul
    Aug 9 '16 at 11:30
  • Could you put the whole controller's code here? It might be helpful. Aug 23 '16 at 5:12

The reason of this behavior is the way Magento 2 full page cache works.

Pages in Magento 2 are rendered depersonalized (without any private information) to be cached for all visitors. Private information is later pulled by javascript and private blocks are updated.

For this purpose there are a set of Denationalization plugins introduced, that flush all sessions when rendering starts.

In your case $resultPage->getConfig()->getTitle() will trigger \Magento\Framework\View\Page\Config::build() and further layout XML generation. The plugin \Magento\Customer\Model\Layout\DepersonalizePlugin::afterGenerateXml calls $this->session->clearStorage() to prevent private data used during rendering.

Thant's why session is empty after $resultPage->getConfig()->getTitle(); call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.