Skip to content

Mukesh Chapagain Blog

  • PHP
    • PHP
    • Laravel
    • WordPress
    • Joomla
  • Magento
    • Magento 2
    • Magento Extension
  • Node.js
    • Node.js
    • Javascript
    • jQuery
  • Database
    • MySQL
    • MongoDB
  • Data Science
    • Machine Learning
    • Recommender System
    • Natural Language Processing (NLP)
    • Sentiment Analysis
    • Python
    • R
  • Categories
    • Blockchain
      • Hyperledger Composer
      • Hyperledger-Fabric
    • Other
      • Cryptography
      • Data Structures & Algorithms
      • Git
      • LaTeX
      • Linux
      • Ubuntu
      • Xubuntu
      • Google
      • Google AppScript
  • About
    • About
    • Contact
    • Privacy Policy

Home » Magento » Magento 2 » Magento 2: Different Ways To Check if Customer is Logged In

Magento 2: Different Ways To Check if Customer is Logged In

December 11, 2021December 7, 2021 by Mukesh Chapagain
Categories Magento, Magento 2 Tags customer, login, Magento, magento2, session
FacebookTweetLinkedInPinPrintEmailShares

This article shows different ways to check if a customer is logged in or not in Magento 2.

1) Using \Magento\Customer\Model\Session class

  • The main issue with this way is that it will not work when page cache is enabled.
  • When page cache is enabled and you use this code, it will not be able to get the logged-in customer ID or get the boolean value of isLoggedIn.
/**
 * @var Magento\Customer\Model\Session
 */
protected $customerSession;

/**
 * ...
 * @param \Magento\Customer\Model\Session $customerSession
 */
public function __construct(
    ...
    \Magento\Customer\Model\Session $customerSession
) {
    ...
    $this->customerSession = $customerSession;
}

/**
 * @return int
 */
public function getCustomerId()
{
    return $this->customerSession->getCustomer()->getId();
}

/**
 * @return bool
 */
public function isCustomerLoggedIn()
{
    return $this->customerSession->isLoggedIn();
}

2) Using Factory Class Magento\Customer\Model\SessionFactory

  • Using Factory class will solve the issue with page cache.
  • We will be able to run this code even if the page cache is enabled.
/**
 * @var Magento\Customer\Model\SessionFactory
 */
protected $customerSessionFactory;

/**
 * ...
 * @param \Magento\Customer\Model\SessionFactory $customerSession
 */
public function __construct(
    ...
    \Magento\Customer\Model\SessionFactory $customerSessionFactory
) {
    ...
    $this->customerSessionFactory = $customerSessionFactory;
}

/**
 * @return int
 */
public function getCustomerId()
{
    $customerSession = $this->customerSessionFactory->create();
    return $customerSession->getCustomer()->getId();
}

/**
 * @return bool
 */
public function isCustomerLoggedIn()
{
    $customerSession = $this->customerSessionFactory->create();
    return $customerSession->isLoggedIn();
}

3) Using HTTP Context class Magento\Framework\App\Http\Context

  • This is useful if we just need to check if the user is logged in or not.
  • Using HTTP Context will work on both cacheable and non-cacheable pages.
  • We also don’t have to work directly with the customer session.
/**
 * @var Magento\Framework\App\Http\Context
 */
protected $httpContext;

/**
 * ...
 * @param \Magento\Framework\App\Http\Context $httpContext
 */
public function __construct(
    ...
    \Magento\Framework\App\Http\Context $httpContext
) {
    ...
    $this->httpContext = $httpContext;
}

/**
 * @return bool
 */
public function isCustomerLoggedIn()
{
    return (bool)$this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
}

Hope this helps. Thanks.

Related posts:

  1. Magento: Programmatically Remove Layout Block
  2. Magento: Redirect Customer to Login page if not logged in
  3. Magento 2: Customer Image/File Upload in Registration & Account Page
  4. Magento2: Programmatically Create Custom Layout XML
Categories Magento, Magento 2 Tags customer, login, Magento, magento2, session
Magento 2: Images of old image gallery not showing in new media gallery
Magento: Programmatically Remove Layout Block

About

Mukesh Chapagain Hi, I’m Mukesh Chapagain — a web developer, programmer, and tech enthusiast. Whether you're a beginner or an experienced developer, you’ll find tips, tutorials, and insights to help you navigate the ever-evolving world of technology. Happy coding! 🚀 about...

         

Subscribe via Email



Categories

Most Viewed

  • Very Simple Add, Edit, Delete, View (CRUD) in PHP & MySQL [Beginner Tutorial] - 435,128 views
  • How to Calculate Inverter & Battery Backup Time? - 430,453 views
  • LaTeX: Generate dummy text (lorem ipsum) in your document - 238,158 views
  • GPG: Remove keys from your public keyring? - 203,599 views
  • Magento: How to get attribute name and value? - 189,657 views

Recent Posts

  • Magento: The store that was requested wasn’t found. Verify the store and try again.
  • Magento2: Check Services version on Adobe Cloud Server
  • Magento 2 API: Add Products to Cart & Checkout Place Order
  • Magento 2 API: Create New Customer
  • Magento 2 API: Get Categories

Recent Posts

  • Magento: The store that was requested wasn’t found. Verify the store and try again.
  • Magento2: Check Services version on Adobe Cloud Server
  • Magento 2 API: Add Products to Cart & Checkout Place Order
  • Magento 2 API: Create New Customer
  • Magento 2 API: Get Categories

Most Viewed

  • Very Simple Add, Edit, Delete, View (CRUD) in PHP & MySQL [Beginner Tutorial] - 435,128 views
  • How to Calculate Inverter & Battery Backup Time? - 430,453 views
  • LaTeX: Generate dummy text (lorem ipsum) in your document - 238,158 views
  • GPG: Remove keys from your public keyring? - 203,599 views
  • Magento: How to get attribute name and value? - 189,657 views

Tag Cloud

admin Adobe Commerce api array attribute block category checkout CLI command line crud currency customer Database error extension git Google grid HTML image Javascript Joomla jQuery latex Linux login Magento magento2 magento 2 module MySQL natural language processing NLP nltk nodejs order PHP product python shopping cart template Ubuntu url Wordpress
© 2026 Mukesh Chapagain Blog
Manage Cookie Consent
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
View preferences
  • {title}
  • {title}
  • {title}