How to check that customer is logged in on frontend in Magento 2.1?

Magento 2.1.1 has an issue when full page cache is disabled - customer data isn't updating after success login. Details

Also sometimes customer data can be still not loaded (waiting for response), so in order to catch this case I prepared following code:

/**
 * This file will check that customer is logged in
 */
define(
    ['jquery', 'Magento_Customer/js/customer-data'],
    function ($, customerData) {
        'use strict';

        var getCustomerInfo = function () {
            var customer = customerData.get('customer');

            return customer();
        };

        var isLoggedIn = function (customerInfo) {
            customerInfo = customerInfo || getCustomerInfo();

            return customerInfo && customerInfo.firstname;
        };

        return function () {
            var deferred = $.Deferred();
            var customerInfo = getCustomerInfo();

            if (customerInfo && customerInfo.data_id) {
                deferred.resolve(isLoggedIn(customerInfo));
            } else {
                customerData.reload(['customer'], false)
                    .done(function () {
                        deferred.resolve(isLoggedIn());
                    })
                    .fail(function () {
                        deferred.reject();
                    });
            }

            return deferred;
        };
    }
);

Navigate to:

vendor/magento/module-customer/CustomerData/Customer.php

public function getSectionData()
    {
        if (!$this->currentCustomer->getCustomerId()) {
            return [];
        }
        $customer = $this->currentCustomer->getCustomer();
        return [
            'fullname' => $this->customerViewHelper->getCustomerName($customer),
            'firstname' => $customer->getFirstname(),
        ];
    }

As we can see, this method will check the exist of customer. And then, it will return the fullname and lastname.

Local storage:

enter image description here

Basicall, your script can be:

        isActive: function () {
            var customer = customerData.get('customer');
            if(customer().fullname && customer().firstname)
            {
                return true;
            }
            return false;
        },

Technically, we can add a login flag to in customer data by overriding the customer data.


define(['Magento_Customer/js/model/customer'], 
    function(customer) {
        return Component.extend({
            someMethod: function () {
                if (customer.isLoggedIn()) {
                   //do smth
                } else {
                   //do smth
                }
            },
        });
    }
);