Check Customer is logged in using knockout js Magento 2
Check Customer is logged in using knockout js Magento 2

Check Customer is logged in using knockout js Magento 2

We can use Magento_Customer/js/model/customercomponent to check if the customer is logged in or not in knockout js.

Check full component here customer.js

We can use isLoggedIn() method. It will return true if customer is loggedIn and return false if customer is not loggedIn

Check below code snippet of JS:

define([
    'uiComponent',
    'Magento_Customer/js/model/customer'
], function (Component, customer) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'MagePrince_Testing/myfile'
        },

        /**
         * Check if customer is logged in
         *
         * @return {boolean}
         */
        isLoggedIn: function () {
            return customer.isLoggedIn();
        }
    });
});

Now you can use isLoggedIn() function in template myfile.html to check customer is loggedIn or not like

<!-- ko if: isLoggedIn() -->
    <span>Customer is logged in</span>
<!-- /ko -->

<!-- ko ifnot: isLoggedIn() -->
    <span>Customer is not logged in</span>
<!-- /ko -->