Shopify: get current logged in user ID in JavaScript

Doua Beri picture Doua Beri · Aug 26, 2014 · Viewed 7.6k times · Source

I'm trying to build an app for shopify and I'm interested if I can get the current logged user ID using javascript api or something similar. I was looking at the ajax api: http://docs.shopify.com/support/your-website/themes/can-i-use-ajax-api and I can see you can get the current products that the current user has added to his shopping cart, but nothing about the user ID.

Is it possible, or am I missing something?

Answer

Rebs picture Rebs · May 19, 2016

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.