How to Check if a Customer is Logged into Magento 2

How to Check if a Customer is Logged into Magento 2

The Magento 2 stores offering impressive features do need to keep a check on them as it can be costly. The way out of this situation is to limit the features based on the customer groups. To implement it, the admin would need to check if a customer is logged into Magento 2 store. Only after confirming if the user is logged in, he/she can be offered the exclusive features.

Let’s say, you are using sign up popup in Magento 2. Sign up popup needs to be restricted the display for the logged in customers as it would be the most annoying thing you can do for your customers! You would need to check whether the user is logged into Magento 2 for doing so.

As the developers are going to need to know the login status of a user, I have posted the solution for the same.

Methods to Check if Customer is Logged into Magento 2:

Note: When PageCache module is on (probably always on production), keep in mind that as soon as layout generation starts, customer session will be cleared by \Magento\PageCache\Model\Layout\DepersonalizePlugin::afterGenerateXml on all cacheable pages. It means that if you now check the login status of the customer in via HTTP context, it will still say ‘yes’, but customer data will not be available in customer session anymore. Make it a point to double-check before trying to access data in customer session. This can easily happen in the block, while is unlikely in action controller since you are not expected to generate layout manually there. It will be generated after the action controller returns an instance of ResultInterface.

Use any of the above methods to check if the user is logged in or not in Magento 2.

If you have any doubts in these methods, please mention them in the Comments section below and I’d be happy to help.

Feel free to share the post with fellow developers on social media.

5
(based on 6 Reviews)

Sanjay is a co-founder at Meetanshi. He is a Certified Magento Developer who loves creating Magento E-commerce solutions. When he is not engrossed with anything related to Magento, he loves to play cricket.

Leave a Reply