Magento 2.2.2: Customer session not working with cache enable
The best practice is to use Magento\Framework\App\Http\Context
to check the customer logged in or not. And, avoiding using Object Manager directly.
For example:
<?php
namespace Vendor\Customer\Block\Account;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Framework\App\Http\Context as HttpContext;
class Customer extends Template
{
/**
* @var HttpContext
*/
protected $httpContext;
/**
* @param Context $context
* @param HttpContext $httpContext
* @param array $data
*/
public function __construct(
Context $context,
HttpContext $httpContext,
array $data = []
) {
parent::__construct($context, $data);
$this->httpContext = $httpContext;
}
/**
* Checking customer login status
*
* @return bool
*/
public function customerLoggedIn()
{
return (bool)$this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
}
}
Use below code:
$ObjectManager= \Magento\Framework\App\ObjectManager::getInstance();
$context = $ObjectManager->get('Magento\Framework\App\Http\Context');
$isLoggedIn = $context->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
return $isLoggedIn;