Shopify analytics with nextjs13

torena
Visitor
2 0 0

Hello,

 

I'm not finding any information on how to setup the shopify analytics for nextjs13. I currently have a component like this : 

'use client';

import {
    AnalyticsEventName,
    ShopifyPageViewPayload,
    ShopifySalesChannel,
    getClientBrowserParameters,
    sendShopifyAnalytics
} from '@shopify/hydrogen-react';
import { useLocale } from 'next-intl';
import { useEffect } from 'react';
const ShopifyAnalytics = () => {
    const locale = useLocale();

    function sendPageView(analyticsPageData: ShopifyPageViewPayload) {
        const payload = {
            ...getClientBrowserParameters(),
            ...analyticsPageData
        } satisfies Partial<ShopifyPageViewPayload>;
        sendShopifyAnalytics({
            eventName: AnalyticsEventName.PAGE_VIEW,
            payload
        });
        console.log(payload);
    }
    // Hook into your router's page change events to fire this analytics event:
    // for example, in NextJS:
    const analyticsShopData = {
        shopId: 'gid://shopify/Shop/<shopid>',
        currency: 'EUR',
        acceptedLanguage: locale.toUpperCase(),
        shopifySalesChannel: ShopifySalesChannel.headless,
        hasUserConsent: true,
    };

    // eslint-disable-next-line react-hooks/exhaustive-deps
    const analytics: any = {
        ...analyticsShopData,
    };

    useEffect(() => {
        sendPageView(analytics);
    }, [analytics]);

    return <></>;
};
export default ShopifyAnalytics;

This is then put in the Layout with the children component to trigger on each page view. But when I send the analytics, the shopId variable is NULL and fails. What am I missing? Something with createStorefrontClient? But I don't see how to implement this in a server component.

Replies 3 (3)

Liam
Shopify Staff
2731 299 769

HI Torena,

 

The shopId can be retrieved from the useShop hook provided by gen. You could it as follows:

import { useShop } from '@shopify/hydrogen-react';

// Inside your component:
const { id: shopId } = useShop();

Notice that the useShop hook should be used inside a function component, and it should be called on every render, not just once.

 

However, it's important to remember that Hydrogen is designed to work with Remix, and it may not work as expected with Next.js. The Hydrogen project structure is tightly integrated with the way Remix handles data fetching, routing, and other core aspects of a React application. Therefore, using Hydrogen with Next.js might require additional configurations or workarounds, which are not officially supported.

 

If you're building a Shopify storefront using Next.js, you might want to consider using the Shopify Storefront API directly, or look into alternative libraries that are designed to work with Next.js.

 

Hope this helps!

Liam | Developer Advocate @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

Filiph
Shopify Partner
7 1 5

Hi there!

 

Yeah, analytics has been completely broken on non-hydrogen storefronts; at least if you want to track both "visitors" and "active carts".

 

Though I did find a workaround a few months back, by doing the following:

  • Grab the storefront token(s) and the `PUBLIC_STOREFRONT_ID` from the hydrogen channel.
  • Make sure the primary Shopify domain is an under the same domain as your headless storefront (eg checkouts. and www.).
  • Optional: Deploy a dummy hydrogen storefront that redirects to deal with "Cart" icon link in the checkout that you for some unexplainable reason can't turn off.
  • Contemplate why you in 2023 have to look for obscure and hacky workarounds on a forum of all places to get something as simple as analytics working with the largest e-commerce service provider in the world.


Now you just have to construct the analytics payload. However, NOTE the use of `ShopifySalesChannel.hydrogen` instead of `ShopifySalesChannel.headless`.

const pageAnalytics: ShopifyPageViewPayload = {
    ...viewPayload,
    shopId,
    shopifySalesChannel: ShopifySalesChannel.hydrogen,
    storefrontId: process.env.PUBLIC_STOREFRONT_ID,
    currency: locale.currency,
    acceptedLanguage: locale.language,
    hasUserConsent: true,
    isMerchantRequest: true,
    ...((pagePropsAnalyticsData as any) || {})
};


For cart events you'd just send a `ShopifyAddToCartPayload` payload with its respective data instead.

 

 

(Intentionally coming of a bit snarky and exaggerated for humors sake, the storefront api is for the most parts superb DX with a few growing pains).

// Filiph, CTO at Nordcom Group Inc.
karvedigital
Shopify Partner
1 0 0

I know this is an old post, but recently i had faced similar issues, while i was trying to integrate Shopify analytics with non-hydrogen setup using a NextJs,

 

So, I created tutorial on how to solve this issue, sharing it here so to help out others. 

https://karvedigital.com/insights/integrating-shopify-analytics-into-your-next-js-custom-storefront