We have got logged-in customer id. We also have got logged-in customer id while Full Page Cache (FPC) is enabled.
Now, we will explore how to check whether a customer is Logged in using JavaScript. We often need to identify customer status in Knockout Component to render based on visitor activity.
Knockout JS is essential to Magento 2, specifically in the mini cart and checkout at the front end. Hence, We often get requirements to get customer details or validate the status of the customer at the front end using JS.
For example, the Render component on checkout is based on the status of the customer or the type of customer using Knockout JS. In such scenarios, we have to check the customer’s status or get details of the customer in JS.
So, let’s check out how we can fulfil such requirements.
How to check customer is Logged in Knockout JS?
We just need to inject Magento_Customer/js/model/customer inside JS in order to get Customer Object in the component.
Create JS File inside your theme or module. Let’s assume we are going to create it inside module with name SbDevBlog_Customer.
So Let’s create customer.js inside.
SbDevBlog/Customer/view/
frontend/web/js directory.
define([
'ko',
'jquery',
'uiComponent',
'Magento_Customer/js/model/customer'
], function (
ko,
$,
Component,
customer
) {
'use strict';
return Component.extend({
/**
* Return customer login status
*
* @return boolean
*/
isLoggedIn: function () {
return customer.isLoggedIn();
}
});
});
That’s it. call the function isLoggedIn() from the KnockOut Template in order to perform operation or render your components.
Please share this article, leave your comment, and feedback.
Checkout My Git Repository: https://github.com/sbdevblog
Note: Please verify the code of this blog and the relevant git repository before using it in production.
🙂 HAPPY CODING 🙂