Back to Top

Get Customer ID Without Session in Magento 2

Updated 15 September 2025

Why not rely only on session?
In Magento 2, developers often use customerSession to fetch the logged-in customer ID.

However, this may fail if full-page cache or Varnish serves a cached page where session data is not available.

Using UserContextInterface

To solve this, Magento provides UserContextInterface.
This interface returns the customer ID without depending directly on session values.

Example implementation

Searching for an experienced
Magento Company ?
Find out More

You can inject UserContextInterface into a helper or class:

namespace Vendor\Customer\Helper;

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

class Data extends AbstractHelper
{
    private $userContext;

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

    public function getCustomerId(): ?int
    {
        return $this->userContext->getUserId();
    }
}

This retrieves the customer ID if the context is set.
Otherwise, it safely returns null.

When to use UserContext vs Session

You should use UserContext when working with APIs, GraphQL, or AJAX calls that may bypass session.
In these cases, it handles identity even under caching and token-based authentication.

On the other hand, session works well on traditional storefront flows where customer login relies on PHP session cookies.

Therefore, session is usually more reliable for frontend templates and blocks.

Combining both for reliability

A hybrid approach gives better coverage across scenarios.
Check session first, and if not available, then fall back to UserContext.

if ($this->customerSession->isLoggedIn()) {
    return (int) $this->customerSession->getCustomerId();
}
return (int) $this->userContext->getUserId() ?: null;

This way, both session-driven pages and API calls can work seamlessly.

Related session-based approach

If you still want to use session while cache is enabled, Magento provides safe methods.
For details, see our guide: How to Get Customer Data from Session When Cache Enabled.

Learn more

For official reference, check the Adobe DevDocs on User Context .

Conclusion

In conclusion, UserContextInterface is ideal for API or cache-heavy environments.
Meanwhile, session remains the go-to option for regular frontend flows.

By combining both approaches, you ensure reliable customer ID retrieval across all scenarios in Magento 2.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


2 comments

  • Pratik Giramkar
    • abhishek (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home