How to Get Customer ID Without Using Session in Magento 2

Magento developers often use customer ID to implement features that are exclusively for logged in customers. Even I have posted solutions where one can get customer addresses by customer ID in Magento 2 and use it to maintain the address database while offering guest checkout. Magento 2 provides a convenient way to get, set, and unset custom session variables using the session object.

Apart from this, the admin may need a customer ID to hide the signup button for already logged in customers, or display a discount offer that is valid only for logged in customers!

I can go one with the examples where a Magento developer will require to get a customer ID. But today, instead I am going to offer an alternate solution to get a customer ID.

You can get customer ID without using session in Magento 2 and hence avoid issues like

  • A NULL value is returned even if the customer is logged in.
  • You have to disable the cache, and hence low page speed.
  • It does not return customer ID.

That’s why I recommend using the below solution which does not generate any issues and doesn’t require disabling cache.

Method to Get Customer ID Without Using Session in Magento 2

Use the below code in the helper file.

<?php

namespace Vendor\Extension\Helper;

use Magento\Authorization\Model\UserContextInterface;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;

class Data extends AbstractHelper
{
    protected $userContext;

    public function __construct(
        Context $context,
        UserContextInterface $userContext
    )
    {
        $this->userContext = $userContext;
        parent::__construct($context);
    }

    public function getLoginCustomerId()
    {
        $customerId = $this->userContext->getUserId();
        return $customerId;
    }
}

That’s all!

Feel free to share the solution with Magento Community via social media.

Thank You.

Table of Contents