How can I access user ID and meta fields in an app embed block?

Solved

How can I access user ID and meta fields in an app embed block?

Laderlappen
Shopify Partner
9 1 4

Good day!

I want to use an app embed block to prevent a user from buying a specific product if they don't have a certain value in their user meta fields which I populated earlier (This will be done with a big popup modal or something similar). 

Is it possible to get access to the logged in user ID and custom meta fields ( I can also switch to user tags if needed) in the app embed block Javascript code?

What info is available to me about the logged in user?
If this is not possible any other ideas on how to achieve this would be much appreciated.

Accepted Solution (1)
Laderlappen
Shopify Partner
9 1 4

This is an accepted solution.

I just got it in the Liquid code of the embedded extension. Liquid provides a bunch of Shopify specific objects for easy access (https://shopify.dev/docs/api/liquid/objects). To get the customer id we just used the liquid customer object like this: "customer.id".

We didn't need to get it in JavaScript.



View solution in original post

Replies 5 (5)
Laderlappen
Shopify Partner
9 1 4

Thank you for the detailed answer! I'll try this and ask a new question if I get stuck.
Accepting this answer.

Laderlappen
Shopify Partner
9 1 4

It seems like the answer I accepted got deleted somehow. When I came to reference it this morning it was gone. 

Aravindan111
Shopify Partner
1 0 0

Did you get the user data? If yes how did you get it?

Laderlappen
Shopify Partner
9 1 4

This is an accepted solution.

I just got it in the Liquid code of the embedded extension. Liquid provides a bunch of Shopify specific objects for easy access (https://shopify.dev/docs/api/liquid/objects). To get the customer id we just used the liquid customer object like this: "customer.id".

We didn't need to get it in JavaScript.



ShaunStarttin
Shopify Partner
10 1 0

For passing data from liquid to JS

 

The easiest way seems to be defining a global variable on `window` in your liquid file and reading it in JS assets. You could also have a top-level unique name to avoid collisions and wrap a bunch of variables. Your liquid block:

 

 

<script>
window.MY_APP_NAME = { customerId: "{{customer.id}}" }
</script>

 

 

Alternately, a Shopify demo uses html attributes and reads them from the DOM (liquid block and js asset). This seems useful to find specific pieces of data in the DOM structure (e.g. loop over all products).