How to determine login status using Additional Scripts?

How to determine login status using Additional Scripts?

RossellaF
Shopify Partner
28 0 6

Hi,

 

I am working on an script for the order status page. My goal is to check if the customer was logged in or not at the time of the purchase. 

 

When I was tracking this through the checkout.liquid file, I was using this logic:

 

 

var logState = {
  {% if customer %}
    'userId' : {{ customer.id | json }},
    'logState' : "Logged In",
    'customerInfo' : {
      'totalOrders' : {{ customer.orders.size | json }},
      'totalSpent' : {{ customer.total_spent | money_without_currency | remove: "," | json }},
    },
  {% else %}
    'logState' : "Logged Out",
   {% if checkout %}
    'totalOrders': {{ checkout.customer.orders.size | json }},
    {% endif %}
  {% endif %}
  'timestamp' : Date().replace(/\(.*?\)/g,''),
  'has_account': {{ checkout.customer.has_account | json }},
   {% if customer.orders.size > 1 or checkout.customer.orders.size > 1 %}
     'customerType' : 'Returning',
     'customerTypeNumber' : '0',
    {% else %}
   'customerType' : 'New',
   'customerTypeNumber' :'1',
  {% endif %}
  'pageType' : 'Log State',
  'event' : 'logState'
}

 

 

However, if I use the same logic in the Additional Scripts, the first {% if customer %} always returns true, even though in the documentation it's mentioned that "The customer object is directly accessible globally when a customer is logged in to their account." 
It returns true for new and existing customers, logged in or logged out.

Is this the expected behaviour? How would you recognize if a customer is logged in or not?

 

 
Reply 1 (1)

gr_trading
Shopify Partner
1919 145 199

Hi @RossellaF ,

 

It seems like you're checking this information in the wrong place. During checkout, users have already entered their email address in Shopify, which uniquely identifies them.


In custom development when we create a guest user flow, if we receive user information, we either register them or load their information if they're an existing user.

May be Shopify doing it in same way, therefore you're always getting the customer object as true in checkout.liquid.

 

To check if a user is already logged in, you should use JavaScript. When a user logs in to the store, set a cookie value. Then, check for the existence of this cookie. If it exists, the user is already logged in before reaching the checkout flow.

 

Hope this will help...

For any custom development WhatsApp or connect at Email ID: [email protected] for quick consultation. | Shopify Free codes
To support Buy Me a Coffee