How to Check if Customer is Logged in or not in Magento 2?

Today's tutorial will explain how to check if the customer is logged in or not in Magento 2. When we are developing any functionality on the basis of customer and guest, there is a requirement to check whether the customer is logged in or not. At times, we also add certain restrictions and allow only logged in customers to access only when they log in. Here, the below-mentioned code can be used to check customers ' logged in data.

It can be checked if the customer is logged in or not using \Magento\Framework\App\Http\Context class. Let's consider the below code:

Steps to check whether a customer is logged in or not in Magento 2 :

You need to use the below code in your block file. Post that, you can call isCustomerLoggedIn() function to check customer logged in or not.

<?php

namespace MD\Helloworld\Block;

class Customer Details extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Magento\Framework\App\Http\Context
     */
    protected $httpContext;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Framework\App\Http\Context              $httpContext
     * @param array                                            $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\App\Http\Context $httpContext,
        array $data = []
    ) {
        $this->httpContext = $httpContext;
        parent::__construct($context, $data);
    }

    /**
     * @return boolean
     */
    public function isCustomerLoggedIn() {
        return $this->httpContext->isLoggedIn();
    }
}
In template file, you can use like this:

/**
 
$isLoggedin = $block->isCustomerLogin();
if($isLoggedin) {
    // customer is logged in
} else {
    // customer is not logged in
}

If you want to check in JavaScript file, you can also check in JavaScript using this below solution. You can add this below code in your JavaScript file and after that retrieve information about customer also. customer.isLoggedIn(); value will be return Boolean value.

/**
define([
    'ko',
    'jquery',
    'uiComponent',
    'Magento_Customer/js/model/customer'
], function (
    ko,
    $,
    Component,
    customer
) {
    'use strict';
    return Component.extend({
      
        /**
         * Check if customer is logged in
         *
         * @return {boolean}
         */
        isLoggedIn: function () {
            return customer.isLoggedIn();
        }
    });
});

We hope that you now finally know how to check if the customer is logged in or not in Magento 2.

In case we missed any needful information, please let us know in the comments below.

That being said, if you still need professional assistance with Magento 2 Certified Professional Developer, feel free to contact us.

Also read: How to Get Customer Data by Customer email in Magento 2?

Magento Support Services