SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH SPECIAL OFFER: ENJOY 3 MONTHS OF SHOPIFY FOR $1/MONTH
How-to-check-customer-is-logged-in-or-not-in-Magento-2-

How to check customer is logged knockout js magento 2

In magento, the fact that you access the website with an existing account or not log in is quite interested by many managers.
In this article I will show you how to check if a client is logged in using knockout js.
We use the isLoggedIn() method to check if the customer is logged in, which returns true if the customer is logged in and false if the customer is not logged in.

Copy and paste this code into your js component file for example file named checkcustomer.js

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

    return Component.extend({
        defaults: {
            template: 'Magepow_CheckCustomer/checkcustommer'
        },

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

Please check the files and change them to match your module.

Now use the isLoggedIn() function previously created in the checkcustomer.js file to check if the user is logged in or not. We will announce a content to customers who have not or are logged in in the file checkcustommer.html

<!-- ko if: isLoggedIn() -->
    <span>You are logged in</span>
<!-- /ko -->
<!-- ko ifnot: isLoggedIn() -->
    <span>You are not logged in</span>
<!-- /ko -->

Or you can call in any .phtml file by following way

<div class="text-account text-hidden" data-bind="scope: 'customer'">
    <!-- ko if: customer().firstname  -->
    <span class="logged-in"
         data-bind="text: new String('<?= $block->escapeHtml(__('Hello!, %1', '%1')) ?>').replace('%1', customer().firstname)">
    </span>
    <!-- /ko -->
    <!-- ko ifnot: customer().firstname  -->
        <?php echo __('Hello! Sign in'); ?>
    <!-- /ko -->
    <script type="text/x-magento-init">
    {
        "*": {
            "Magento_Ui/js/core/app": {
                "components": {
                    "customer": {
                        "component": "Magento_Customer/js/view/customer"
                    }
                }
            }
        }
    }
    </script>
</div>

Please leave a comment if you have any questions about the article