Shopify: get current logged in user ID in JavaScript

I've found the __st variables unreliable (__st_uniqToken for one). I believe the proper way to do this in Javascript is using the following call:

ShopifyAnalytics.lib.user().id()

You can also get the unique user id (non-logged in id) with:

ShopifyAnalytics.lib.user().properties().uniqToken

This is also the only reliable way to get it on the checkout page. I previously used __st_uniqToken, but it has since stopped working.

NOTE This is no longer 100% fool-proof. Shopify have AGAIN changed how their site works on the landing and thank-you pages. I've had to resort to the following function to get a user id 'reliably'.

var user_id = function() {
    try {
        return ShopifyAnalytics.lib.user().id();
    } catch(e) {}
    try {
        return ShopifyAnalytics.lib.user().properties().uniqToken;
    } catch(e) {}
    try {
        return ShopifyAnalytics.lib.user().anonymousId();
    } catch(e) {}
    return __st_uniqToken;
};

Developing for Shopify is a true nightmare. I spend 50% of my time un-breaking my product every few weeks because them.


In layout.liquid file you can add this code to define global customerId variable

{% if customer %}
  <script type="text/javascript">
   window.customerId = "{{ customer.id }}";   
  </script>
{% endif %}

You can try __st.cid in JavaScript for getting customer id.