Skip to main content

Fast Simon Analytics Integration for Shopify Hydrogen

This guide outlines how to integrate Fast Simon Analytics into your Shopify Hydrogen storefront. By following these steps, you'll be able to track user behavior and gain valuable insights into their journey, leveraging both Shopify's built-in analytics and Fast Simon's custom reporting.

Core Concepts

Shopify Hydrogen provides a powerful Analytics API that allows you to hook into various storefront events. While this is a great starting point, it doesn't provide all the context needed for advanced analytics. For example, when a user views a product, it doesn't automatically tell us how they arrived at the product page (e.g., from a search result, a collection page, or an autocomplete suggestion). This is where the Fast Simon SDK and its utilities come into play.

Our SDK integrates seamlessly with Shopify's Analytics events while providing the necessary tools to capture additional data points required for comprehensive analysis.


Step-by-Step Implementation

1. Integrate the FastSimonAnalytics Component

The FastSimonAnalytics component subscribes to Shopify's Analytics events and sends data to Fast Simon's reporting service.

Why This Step?

This component acts as the entry point for the analytics integration. It hooks into the Hydrogen Analytics.Provider and listens for core events such as product views, collection views, search views, and cart updates.

Implementation

  1. Create a Custom Analytics Component:

    create a new file named FastSimonTracking.tsx in the components directory of your Hydrogen project. Add the following code to the file:

    import {FastSimonAnalytics} from '@fast-simon/storefront-kit';
    import {useAnalytics} from '@shopify/hydrogen';

    export function FastSimonTracking({storeId, uuid, storeDomain}: {storeId: string, uuid: string, storeDomain: string}) {
    const analyticsContextValue = useAnalytics();
    return <FastSimonAnalytics storeId={storeId} uuid={uuid} storeDomain={storeDomain} searchPersonalization={true} collectionPersonalization={true} analyticsContextValue={analyticsContextValue}/>
    }
  2. Import the FastSimonTracking Component:

    In your root layout file (usually root.tsx), import the FastSimonTracking component:

  3. Add Environment Variables: In your loader function in root.tsx, add the needed environment variables:

    export async function loader({ context }: LoaderArgs) {
    return {
    fastSimon: {
    uuid: args.context.env.FAST_SIMON_UUID,
    storeId: args.context.env.FAST_SIMON_STORE_ID,
    storeDomain: args.context.env.PUBLIC_STORE_DOMAIN
    },
    ...
    }
    }
  4. Invoke Inside Analytics.Provider: Inside the <Analytics.Provider> in the root layout, invoke the FastSimonTracking component, passing the necessary parameters from the loader data:

    <Analytics.Provider
    cart={data.cart}
    shop={data.shop}
    consent={data.consent}
    >
    <PageLayout {...data}>{children}</PageLayout>

    <FastSimonTracking storeId={data.fastSimon.storeId} uuid={data.fastSimon.uuid} storeDomain={data.fastSimon.storeDomain}/>

    </Analytics.Provider>

2. Configure Content Security Policy (CSP)

You need to allow requests to Fast Simon's reporting endpoint in your Content Security Policy.

Why This Step?

This component acts as the entry point for the analytics integration. It hooks into the Hydrogen Analytics.Provider and listens for core events such as product views, collection views, search views, and cart updates.

Implementation

In your entry.server.tsx file, add https://ping.fastsimon.com to the connectSrc array in your CSP configuration:

const {nonce, header, NonceProvider} = createContentSecurityPolicy({
shop: {
checkoutDomain: context.env.PUBLIC_CHECKOUT_DOMAIN,
storeDomain: context.env.PUBLIC_STORE_DOMAIN,
},
connectSrc: ['https://ping.fastsimon.com'],
imgSrc: [
"'self'",
"https://cdn.shopify.com",
"https://shopify.com",
"https://demo-shopify.fastsimon.com",
"https://assets.instantsearchplus.com",
"http://magento.instantsearchplus.com"
],
});

3. Enhance Collection Page Analytics

On collection pages, it's important to know the user's journey, including applied filters, sorting, and the specific product they clicked.

Why This Step?

Shopify's default collection_viewed event doesn't provide details about the applied filters or sort order. We need to add custom data to understand the user's filtering behavior. Additionally, we need to track where the user came from to the product page (search results / collection page / autocomplete).

Implementation

  1. Import FastSimonReporting: Import the FastSimonReporting utility in your collection page component (file collection.$handle.tsx).
    import { FastSimonReporting } from '@fast-simon/storefront-kit';
  2. Add Custom Data to Analytics.CollectionView: Add the custom data to your collection view component:
    <Analytics.CollectionView data={{collection: {handle: collection.handle, id: collection.category_id}}} customData={collection} />
  3. Prepare Data on Product Click: Add a click event handler to the product card to prepare data before the user navigates to the product page:
    const onProductClick = (productId) => {
    FastSimonReporting.prepareProductSeenFromCollectionData({
    productId,
    productPosition: collection.items.findIndex(item => item.id === productId) + 1,
    sortBy: collection.sort_by,
    pageNumber: collection.p,
    categoryId: collection.category_id,
    categoryName: collection.category_name
    });
    }
    prepareProductSeenFromCollectionData: This function stores temporary data in localStorage that will be used when the product page is loaded. This data enriches the reporting with additional information (e.g., category, position in the grid, sort, etc.).

4. Enhance Search Page Analytics

Similar to collection pages, it's important to track the user's search query, any applied filters, sorting and what product they eventually clicked on.

Why This Step?

Shopify's default search_viewed event doesn't provide details about the applied filters or sort order. Also, we need to know where the user came from to the product page (search results / collection page / autocomplete).

Implementation

  1. Import FastSimonReporting: Import the FastSimonReporting utility in your search page component (file search.tsx).
    import { FastSimonReporting } from '@fast-simon/storefront-kit';
  2. Add Custom Data to Analytics.SearchView: Add the custom data to the Search view component:
    <Analytics.SearchView data={{searchTerm: term, searchResults: result}} customData={result} />
  3. Prepare Data on Product Click: Add a click event handler to the product card to prepare data before the user navigates to the product page:
    const onProductClick = (productId) => {
    FastSimonReporting.prepareProductSeenFromSerpData({
    productId,
    productPosition: result.ids.findIndex(id => id === productId) + 1,
    query: term,
    sortBy: result.sort_by,
    pageNumber: result.p
    })
    }
    prepareProductSeenFromSerpData: This function stores temporary data in localStorage that will be used when the product page is loaded. This data enriches the reporting with additional information (e.g., search query, position in the grid, sort, etc.).

5. Track Autocomplete Interactions

When a user interacts with the autocomplete feature, we need to track both clicked collections and products from the autocomplete.

Why This Step?

Autocomplete is an important part of the user experience, and we need to know what products or collections users are interacting with through it.

Implementation

  1. Prepare Data on Collection Click: Add a click event handler to the collection item in the autocomplete results:
    const onAutocompleteItemClicked = (collection) => {
    FastSimonReporting.prepareCollectionSeenFromAutocompleteData({
    collectionId: collection.id,
    query: term.current
    })
    }
    prepareCollectionSeenFromAutocompleteData: This function is used to store temporary data to the localStorage that will be used when collection page is loaded, This data is used in our reporting and enrich it with the additional information (e.g., original search query).
  2. Prepare Data on Product Click: Add a click event handler to the product item in the autocomplete results:
    const onAutocompleteItemClicked = (product) => {
    FastSimonReporting.prepareProductSeenFromAutocompleteData({
    productId: product.id,
    query: term.current,
    sku: product.s
    })
    }
    prepareProductSeenFromAutocompleteData: This function is used to store temporary data to the localStorage that will be used when product page is loaded, This data is used in our reporting and enrich it with the additional information (e.g., original search query).

6. Upsell & Cross-sell Analytics

When presenting product recommendations (e.g., upsell or cross-sell widgets) on your Shopify Hydrogen storefront, Fast Simon allows you to capture granular analytics about how customers interact with these recommended products. With a minimal amount of code, you can track product clicks and product impressions (or “views”) to gain deeper insights into which recommendations are driving conversions.

Implementation

  1. Capture Product Click Events: When a user clicks a product in a widget, you should prepare and send the appropriate analytics data to Fast Simon. Adding a dedicated callback for this event is required:

    import {FastSimonReporting} from '@fast-simon/storefront-kit';
    // Callback to prepare the data before the user navigates away
    const onRecommendationsProductClick = (productId, position, widgetId) => {
    FastSimonReporting.prepareProductSeenFromRecommendations({
    productId: productId,
    productPosition: position,
    widgetId: widgetId
    });
    };
    • productId - The unique ID of the product that was clicked.
    • productPosition - The position of the product in the widget.
    • widgetId - An identifier for the recommendation widget itself (if available), so you can distinguish between different widget placements or types.
  2. Track Product Impressions: When rendering your recommendation widget, you need to log that these products were “seen” by the customer. To do this, wrap (or place) the Analytics.CustomView component after the widget is rendered. This approach lets Fast Simon know which recommended products (and widget) were visible to the user.

    <div>
    <FastSimonWidget
    // rest props
    renderProduct={(product, pos) => (
    <ProductItem
    key={product.id}
    product={product}
    onProductClick={(productId) =>
    onRecommendationsProductClick(productId, pos, widget?.widget_id)
    }
    loading={pos > 4 ? 'lazy' : 'eager'}
    />
    )}
    />
    // add the below custom event and pass the widget data
    <Analytics.CustomView
    type="recommendations_products_seen"
    customData={widget}
    />
    </div>

7. Personalization (Optional)

Prerequisites

  • Ensure you have completed the Analytics integration by following this guide.
  • Your Hydrogen storefront must be running storefront-kit version 1.4.0 or higher.

Overview

Fast Simon's personalization feature seamlessly integrates with Shopify Hydrogen. With just a single step, you can enable this functionality, and Fast Simon will handle the rest.


Implementation Guide

Step 1: Create an API Route

  1. In your Hydrogen project, navigate to the routes directory.
  2. Create a new file and name it fast-simon-product-tracking.ts.
  3. Add the following code to the newly created file:
import {ActionFunctionArgs} from '@shopify/remix-oxygen';
import {fastSimonTrackingUtils} from '@fast-simon/storefront-kit';

export let loader = ({ request, context }) => {
return fastSimonTrackingUtils.getViewedProducts({ request, context });
};

export async function action({request, context}: ActionFunctionArgs) {
return fastSimonTrackingUtils.setPersonalizationData({request, context});
}

Once this route is set up, Fast Simon will automatically track product views and apply personalization logic to enhance the shopping experience.


By completing this step, your Shopify Hydrogen storefront will leverage Fast Simon's advanced personalization capabilities, driving improved engagement and conversions.

Conclusion

By integrating the Fast Simon SDK and following this guide, you can enhance your Shopify Hydrogen storefront's analytics capabilities. You'll gain access to valuable insights that are not provided out of the box by Shopify, allowing you to better understand your users' behavior and optimize their shopping experience.