In this post, we will be looking at how to check customer is logged in or not in Magento 2.
We can check it by following methods:
- Using customer session
- Using httpContext
Let’s start to review both method one by one.
- Using customer session
You can get customer data from customer sessions when a cache is disabled or in the controller.
<?php
namespace Mageclues\Customer\Controller;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Model\Session;
class Index extends \Magento\Framework\App\Action\Action
{
protected $_customerSession;
public function __construct(
Context $context,
Session $customerSession
) {
$this->_customerSession = $customerSession;
parent::__construct($context);
}
public function execute()
{
if($this->_customerSession->isLoggedIn()) {
// Customer is logged in
} else {
// Customer is not logged in
}
}
}
The above code will not work in block or helper when a cache is enabled.
Because when a cache is enabled, customer session will be cleared by \Magento\PageCache\Model\Layout\DepersonalizePlugin::afterGenerateXml on all cacheable pages once layout generation started.
So that we can’t get customer data from \Magento\Customer\Model\Session.
<block class="Mageclues\Customer\Block\CustomerBlock" name="mageclues_customer_block" template="Mageclues_Customer::customer/details.phtml" cacheable="false" />
You can use cacheable=false for your custom block in layout and get all customer session data in your custom block. But there is one drawback of this method is that when you use cacheable=false XML attribute in your layout entire page will disable Full Page Cache for the whole page and making the page loading performance extremely slow.
2. Using httpContext
You need to inject \Magento\Framework\App\Http\Context in your Block or Helper. We have injected into my custom helper.
<?php
namespace Mageclues\Customer\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
class Data extends AbstractHelper
{
protected $_httpContext;
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Framework\App\Http\Context $httpContext
) {
$this->_httpContext = $httpContext;
parent::__construct($context);
}
public function getIsCustomerLoggedIn()
{
return (bool)$this->_httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
}
}
This getIsCustomerLoggedIn() function will return a boolean value. If the customer is logged in it will return true and when the customer is not logged in it will return false.
I hope this blog is useful for you. please leave a comment for query and review.
Thank You!
Thanks for the blog, it is really helpful !