Correct way to send data to your app from web pixels?

Hi everyone, university student here building a Shopify app as a senior project. I have a web pixel extension that subscribes to the product_viewed event. I want to post some data from that event to my Shopify app.

The current route I’m trying is using an app proxy, but I’m running in to a restrictedURL error when I try to post the data:

RestrictedUrlError: Requests are not allowed to the same origin: https://tosh-dev-story.myshopify.com/apps/collect

Does anyone have any input on the best pattern to follow for posting this data to my Shopify app?

Here is the current web pixel extension code that is trying that request:

register(({ analytics, browser, init, settings }) => {
  // Get shop from the current page URL or from pixel context
  const shopDomain = init?.context?.document?.location?.hostname;
  const collectUrl = `https://${shopDomain}/apps/collect`;

  analytics.subscribe("product_viewed", (event) => {
    let payload = {
      client_id: event.clientId,
      timestamp: event.timestamp,
      product: event.data.productVariant,
      url: event.context.document.location.href,
    };
    console.log("[Pixel] product viewed ", payload);
    // Post data to server. Does not handle any response, it is up to the server to validate and handle the data.
    fetch(collectUrl, {
      method: "POST",
      mode: "no-cors",
      headers: {
        "Content-Type": "application/json", // Indicate that the body is JSON
      },
      body: JSON.stringify(payload),
    });
  });
}

I have the app proxy set up in my shopify.app.toml file:

[app_proxy]
url = "/api/collect"
prefix = "apps"
subpath = "collect"

I have also tried re-installing the app as I understand the app proxy is set up at installation time.

Thanks in advance!

Hey Tosh. There’s no need to use the app proxy here IMO, and it looks like that’s the route cause of the error message.

There are few things to keep in mind when building storefront/client accessible analytics:

1.) Security. How will you handle a malicious actor spamming your collection endpoint(s). Google Analytics et al, will have some refresh/remove token approach.
2.) Scale. I’d suggest keeping your analytics collection endpoint separate from your admin application.
3.) Time-series database. You absolutely CAN use regular SQL databases to store analytics data, but it’s not ideal for many reasons.

I’d really recommend using a Cloudflare worker as an analytics collection endpoint, and using ‘Workers analytics engine’ to store and query the data!

1 Like