Shopify / hydrogen

Hydrogen lets you build faster headless storefronts in less time, on Shopify.
https://hydrogen.shop
MIT License
1.21k stars 243 forks source link

Analytics Provider, Customer Privacy API and Privacy Banner #1789

Closed wizardlyhel closed 1 month ago

wizardlyhel commented 3 months ago

Support for Customer Privacy API and better Analytics DX

Proposed developer experience

1. Return the consent configuration

In your root.tsx loader return the consent configuration

export async function loader({context}: LoaderFunctionArgs) {
  return defer({
      // ...other root loader data
+     consent: {
+       checkoutRootDomain: env.PUBLIC_CHECKOUT_DOMAIN,
+       storefrontAccessToken: env.PUBLIC_STOREFRONT_API_TOKEN,
+     }
  });
});

2. Add the <Analytics> for facilitating analytics events and instrumenting page view and cart events.

<Analytics> props

+ import { Analytics } from '@shopify/hydrogen';

export default function App() {
  const data = useLoaderData<typeof loader>();

  return (
    <html lang="en">
      <body>
+        <Analytics.Provider
+           cart={data.cart}
+           consent={data.consent}
+           shop={data.shop}
+           customData={{foo: 'bar'}} // (optional) will be added to all event payloads
+        >
          <Layout {...data}>
            <Outlet />
          </Layout>
+        </Analytics.Provider>
      </body>
    </html>
  );
}

3. Add page view event for product, collection, cart, search views.

In your product route files,

+ import { Analytics } from '@shopify/hydrogen';

export default function Product() {
  const {product, variants} = useLoaderData<typeof loader>();
  const {selectedVariant} = product;
  return (
    <div className="product">
      <ProductImage image={selectedVariant?.image} />
      <ProductMain
        selectedVariant={selectedVariant}
        product={product}
        variants={variants}
      />
+      <Analytics.ProductView 
+        data={{
+          product: {
+            id: product.id,
+.           title: product.title,
+.           handle: product.handle,
+          }
+         }}
+      />
    </div>
  );
}

4. Publish your own custom events

Anywhere within <AnalyticsProvider>, use the useAnalyticsProvider hook to give you the function to publish additional events.

+ import { useAnalytics } from '@shopify/hydrogen';

export function AnalyticsCheckbox({name}) {
  const {publish} = useAnalytics();
  return (
    <input type="checkbox"
+      onChange={(event) => {
+         publish('custom_checkbox_updated', {
+           name,
+           value: event.targetSrc.checked
+         })
+      }}
    />
  );
}

5. Subscribe to analytics events

Anywhere within <AnalyticsProvider>, use the useAnalyticsProvider hook to give you the function to subscribe to analytics events published within the provider.

+ import { useAnalytics } from '@shopify/hydrogen';

+ export function CustomAnalytics() {
+   const {subscribe} = useAnalytics();
+   useEffect(() => {
+     subscribe('page_viewed', (data) => {
+       console.log('CustomAnalytics - Page viewed:', data);
+     });
+     subscribe('product_viewed', (data) => {
+       console.log('CustomAnalytics - Product viewed:', data);
+     });
+     subscribe('checkbox_updated', (payload) => {
+       console.log('CustomAnalytics - Checkbox updated:', data);
+     });
+     subscribe('cart_updated', (data) => {
+       console.log('CustomAnalytics - cart updated:', data);  // {previousCart, currentCart}
+     });
+     subscribe('product_removed_from_cart', (data) => {
+       console.log('CustomAnalytics - Product removed from cart:', data);
+     });
+   }, []);
+ 
+   return null;
+ }

WHAT is this pull request doing?

HOW to test your changes?

Post-merge steps

Checklist

shopify[bot] commented 2 months ago
Oxygen deployed a preview of your hl-analytics-manager branch. Details: Storefront Status Preview link Deployment details Last update (UTC)
subscriptions ✅ Successful (Logs) Preview deployment Inspect deployment April 10, 2024 5:52 PM
third-party-queries-caching ✅ Successful (Logs) Preview deployment Inspect deployment April 10, 2024 5:52 PM
vite ✅ Successful (Logs) Preview deployment Inspect deployment April 10, 2024 5:51 PM
skeleton ✅ Successful (Logs) Preview deployment Inspect deployment April 10, 2024 5:51 PM
optimistic-cart-ui ✅ Successful (Logs) Preview deployment Inspect deployment April 10, 2024 5:51 PM
custom-cart-method ✅ Successful (Logs) Preview deployment Inspect deployment April 10, 2024 5:51 PM

Learn more about Hydrogen's GitHub integration.

github-actions[bot] commented 1 month ago

We detected some changes in packages/*/package.json or packages/*/src, and there are no updates in the .changeset. If the changes are user-facing and should cause a version bump, run npm run changeset add to track your changes and include them in the next release CHANGELOG. If you are making simple updates to examples or documentation, you do not need to add a changeset.

jonrrivera commented 3 weeks ago

so how do we implement this ? :)

wizardlyhel commented 3 weeks ago

@jonrrivera Please follow the readme in example https://github.com/Shopify/hydrogen/tree/main/examples/analytics

We are working on an official tutorial on shopify.dev

j-Riv commented 2 weeks ago

@wizardlyhel the analytics example that you linked above is marked unstable, is this still the case or are we ok to use this in production? I'm trying to get Google Analytics and Meta Pixel running on our Hydrogen Store. Thank you.

wizardlyhel commented 2 weeks ago

We are just ironing out some bugs when used with 3p consent management tools. Other than that, the api interface is fairly stable . We don't anticipate any more big changes

j-Riv commented 2 weeks ago

@wizardlyhel is there any way to test that custom pixels are actually firing?

wizardlyhel commented 2 weeks ago

@j-Riv You can use this as an example to see console logs when the events are firing https://github.com/Shopify/hydrogen/blob/main/examples/analytics/app/components/CustomAnalytics.tsx

Make sure to include this component in your root.tsx within <Analytics.Provider>

shubhambitqit commented 4 days ago

@wizardlyhel I tried following the example but still unable to see any logs.

wizardlyhel commented 3 days ago

The unstable version didn't have much error warnings. The stable version will let you know what's missing. Double check the following:

  1. Check that you have the customer privacy cookie banner turned on in your Shopify admin (This won't be a requirement in the next release)
  2. Make sure you have PUBLIC_STOREFRONT_API_TOKEN, PUBLIC_STORE_DOMAIN, PUBLIC_CHECKOUT_DOMAIN defined in your local .env. Do not use the private token's value in place of the PUBLIC_STOREFRONT_API_TOKEN's value. If you are testing in production, make sure PUBLIC_CHECKOUT_DOMAIN is in the storefront's environment variables.
  3. If you are overriding <Analytics.Provider>'s canTrack property, make sure this callback returns a true at some point. If it doesn't return true, no analytics will be sent
  4. Make sure there is no content security error or network error to the checkout domain url in console log
shubhambitqit commented 3 days ago

@wizardlyhel Thanks for the reply. I am following all the points but I am getting a unauthorized error in my console.log though, for this url https://checkout.hydrogen.shop/api/unstable/graphql.json Screenshot from 2024-05-29 12-14-08

wizardlyhel commented 2 days ago

Make sure the PUBLIC_CHECKOUT_DOMAIN in your .env file and also in storefront custom environment variables isn't set to checkout.hydrogen.shop but instead to the domain url of your own checkout.

If you don't know what that is, navigate to the checkout of your own store and copy that domain value and set it for PUBLIC_CHECKOUT_DOMAIN