Store variable from backend and include it into JS file

Hello there,

I started yesterday developping my first app. Im looking 2 things :

  • I made a backend page and user can enter tracking code but I don’t know how to store it ? Can I use metafields ?
  • Then, once this data stored I need to add it into javscript code. When reading docs it seems I need javascript file but how can I add my variable into the JS code ??

Thank you :slightly_smiling_face:

What is the tracking code’s purpose? Is it for a shipment/order, product, or site analytics?

If it’s for a shipment, you would use the fulfillment APIs (creating a fulfillment, or creating a Fulfillment Service) and specify the tracking code. Shopify would handle displaying the tracking code in the order details pages for admin and customer.

If it’s something related to a product rather than specific orders/users, you could use a metafield to store it.

When using a metafield, it can be accessed in the liquid code and embedded into the html as an attribute (eg, data-my-field=“{{ … }}”) or a variable in a script section. Then use javascript to access that attribute or variable.

Or if it’s a public metafield, you could also access it from javascript using the Storefront API, say if you had a theme that behaved more like a SPA.

Oh thank you for this wonderful answer :slightly_smiling_face:

Yes if for tracking purposes. If goog idea i will use data-var and get it into my js file.
I will add it to all pages ? Cause I need to track also order

I’m still not sure what kind of tracking purpose. Can you describe it more please?

Can you please also describe what you mean by tracking orders?

Yes for setup hotjar. I want developping a app for that :slightly_smiling_face: