The check is as follows:

The Following code is supposed to check if a customer is logged in anywhere

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
   // customer login action
  • this is working or not – HIren Kadivar Feb 13 '19 at 15:49
  • It works only when visiting the cart page; in any other pages it does not; however the template where the check is stored, shows in all pages – Julian Murillo Feb 13 '19 at 15:57
  • You can't access if the page is cached because of magento unset session for cached page. You can access this way shopping cart, checkout, customer account page. Avoid to use \Magento\Framework\App\ObjectManager::getInstance() – Sohel Rana Feb 13 '19 at 16:08
  • Hi Sohel; is there then not possible to check that on any page? – Julian Murillo Feb 13 '19 at 16:14

You can find the why part is in this answer

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.

You can check the login by httpContext it works in all the pages.

private $httpContext;
public function __construct(
    \Magento\Framework\App\Http\Context $httpContext
) {
    $this->httpContext = $httpContext;

public function isLoggedIn()
    $isLoggedIn = $this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
    return $isLoggedIn;
| improve this answer | |

You just need to replace

$customerSession = $objectManager->get('Magento\Customer\Model\Session');


$customerSession = $objectManager->create('Magento\Customer\Model\Session');

When user is logged in, it returns 1 and when not, it returns blank.

Working for me.

| improve this answer | |

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.