Using fetch in theme app extenstion

Hi guys,

I’m developing my first theme app extension, which will retrieve data from an endpoint and display the fetched results. I wasn’t able to find a similar example, so I’d like to confirm if the approach I’m planning to use is correct:

  1. A JavaScript file will be included in the extension.
  2. This JavaScript file will use the fetch method to retrieve data and update a specified DOM element with the response.
  3. To ensure the request is authorized, proxy URLs will be used.

Is the approach above correct, or is there a more efficient solution?

Thanks in advance.

Hey,

This approach is correct and I’ll show how you can do it because I did it before.

  • In your app extensions folder where you have, update the liquid file in our app extension folder.
  • app/extensions/your-ui-extensions/blocks/your-file.liquid: Update this file to this
{% schema %}
{
  "name": "Hello World",
  "target": "body",
  "settings": [],
  "javascript": "storefront.js"
}
{% endschema %}

and include storefront.js file in the assets folder where you’ll call the fetch method. This is called Shopify Theme UI App embeds, you may need to activate your app embeds from the Shopify theme editor.

I hope this answer your question

1 Like

Hey @ilias_haddad,

Thank you so much for your response, it has been incredibly helpful!

By the way, is it possible to return liquid in the response?

No worries, can you elaborate more? in the response from the fetch API.

In that case, you can use the Shopify app proxy to render liquid content in response (App proxy) and use the fetch API in the extensions JS code

Yes, that’s exactly what I need. Thank you for sharing the link.