How to check if a user is logged in in Magento 2

Magento 2

Recently i had to do something very simple: Show a button in the product listing page of a Magento 2 depend if the use was logged in or not. Just do a $session->isLoggedIn() one would say, right? It turns out that this is way more from the truth than i initially though.

I added my code checked the page and it looked good. I openend a private window, navigated to my development environment and logged in. It didn't work. How's that possible?

MageTested.com (ad)

Do you want your Magento store to be more reliable? Tired of things that suddenly break the checkout process without anyone noticing? You can hire my services to kickstart End-2-End testing for your Magento store. This way you know for sure that your store is behaving as expected before releasing that new feature or that update.

View MageTested.com for more information.

Depersonalization

The answer to this is: depersonalization. Let met explain: Magento uses all kinds of cache mechanisms to speed up a webshop. One of those caches is the full page cache. This caches (you guessed it already) the whole page. This means that when the page is in the cache, your code won't be executed anymore. So if you're logged in or not, what's in the cache is served to you.

Now, there are some exceptions to this rule. The FPC works on a customer group level. This way group A can get a different page than group B.

Before Magento is going to render the layout, it scrubs personal data from the different kinds of sessions. This also includes the logged in flag.

Atwix has a blog with more in depth information about this: Session depersonalization in Magento 2, why and how?

But how to check if someone is logged in?

So is it possible to check if someone is logged in in your .phtml templates? There sure is, there are even several methods available.

Customer group

Remember that the content is cached by customer group? This means that you can check to which customer group the current customer belongs. If this is customer group = 0, then it means there not logged in:

use Magento\Customer\Model\Session\Proxy as SessionProxy;

class SuperFancyFunctionality
{
    /**
     * @var SessionProxy
    */
    private $session;

    public function __construct(
        SessionProxy $session
    ) {
        $this->session = $session;
    }

    public function superFunctionality()
    {
        if ($this->session->getCustomer()->getGroupId() != \Magento\Customer\Model\GroupManagement::NOT_LOGGED_IN_ID) {
            // This user is logged in.
        }
    }
}

Using javascript

An other method is to use javascript. This way you can show/hie activate/deactivate parts of your website. This is quite simple:

define(['Magento_Customer/js/model/customer'], function (customer) {
    if (customer.isLoggedIn()) {
        // Do your magic.
    }
});
Want to respond?