Magento 2 – Fix Customer Session Not Working Except on Customer Page

customercustomer-sessionmagento2magento2.0.8session

app/code/Vendore/Module/Block

<?php
namespace Vendor\Module\Block;
class CustomerLink extends \Magento\Framework\View\Element\Template
{
    protected $_customersession;
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Customer\Model\Session $session
    ) {
        parent::__construct($context);
        $this->_customersession=$session;
    }        
    public function sessionCheck()
    {
        return $this->_customersession->isLoggedIn();
    }

}

app/code/Vendore/Module/view/frontend/template

<?php
if($block->sessionCheck())
{
    echo 'logged in';
}
else
{
    echo 'logged out';
}
?>

It works only in customer page and checkout/cart page, remaining page it return false even customer logged in.

so I decided to use \Magento\Framework\App\Http\Context $httpContext this return right boolean value in entire website but how to get customer details using httpContext.

why \Magento\Customer\Model\Session is only working in customer page?

note: all caches are in enable mode.

Best Answer

To have access to real data in Magento 2 session you have to apply one of the following

  • Do it on non-cacheable page.
  • Disable full page cache.
  • Set $this->$_isScopePrivate = true for block where you are trying to access session.

Why:

Magento 2 is rendering public and private content for cacheable pages separately.

During cacheable page rendering Magento is cleaning all data that can be specific to a particular user (unsetting private data). Then separate ajax request is performed to load all private information and update blocks.

That's why session is empty during rendering.

The responsibility of cleaning private data lies on several depersonalization plugins. Customer session for example is cleaned by \Magento\Customer\Model\Layout\DepersonalizePlugin.

You can see conditions in which depersonalization will apply in \Magento\PageCache\Model\DepersonalizeChecker::checkIfDepersonalize

What are cacheable/non-cacheable pages:

In short words, cacheable page is any page that does not include non-cacheable blocks (blocks with cacheable="false" attribute in layout declaration). Correspondingly, pages with non-cacheable blocks are non-cacheable. :)

Here you can find the actual check: \Magento\Framework\View\Layout::isCacheable

Cacheable page examples: Category, Product view pages, CMS pages

Non-cacheable page examples: Customer account and checkotu pages

There is a more detailed Magento 2 Caching Overview by Alan Kent

Related Topic