I'm calling the following helper but getCustomerId is returning NULL when I have cache enabled. If I disable all cache, then I can return the customer's ID.

namespace Company\Module\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
  private $_customerSession;

  public function __construct (
    \Magento\Customer\Model\Session $customerSession
  ) {
    $this->_customerSession = $customerSession;

  public function getCustomerId()
    return $this->_customerSession->getCustomerId();

I've also tried return $this->_customerSession->getCustomer()->getId(); which also returns NULL

Now if I inject the Object Manager instead, I get my desired result and it returns the customerId even with cache enabled:

public function __construct(
    \Magento\Framework\ObjectManagerInterface $objectmanager
  ) {
    $this->_objectManager = $objectmanager;

  public function isBrandingCustomer()
    $customerSession = $this->_objectManager->create("Magento\Customer\Model\Session");
    return $customerSession->getCustomerId();

So my question is, How can I return the customer's ID from $customerSession with cache enabled and without using Object Manager?


1 Answer 1


You need to first be aware how to Magento cache work. You can't use customer ID in cachable pages. Why? Cause when you have unique version of website for every user - it is not from cache.

By default Magento 2 cache hash doesn't include customer ID. So you have wrong approach. You can use customer ID only on non-cached pages as cart/checkout or during order progress or customer section.

For rest of cases you should change your approach. You should display this content using JavaScript. There is special feature for it in Magento. You can use customerData. Magento makes AJAX request about sections when user is logged. Then this content is saved in localStorage. You can add plugin and inject there your extra customer attribute. Then you will have access to it from javascript level.

When you really need to use it in PHP, then you need to modify magento cache hash. Then you can e.g prepare another cache for Gender male and another for gender female. But unique cache for ID => is not a cache :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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