---
title: "Integrate with a Shopify Hydrogen store"
description: "Learn how to integrate with a Shopify Hydrogen store, or with any headless Shopify store using a custom storefront"
url: "https://developers.klaviyo.com/en/docs/integrate_with_a_shopify_hydrogen_store"
category: "Integrate with Klaviyo"
lastUpdated: "2026-11-09"
related: ["https://developers.klaviyo.com/en/docs/llms.txt"]
---

# Integrate with a Shopify Hydrogen store

> This is the Markdown version of https://developers.klaviyo.com/en/docs/integrate_with_a_shopify_hydrogen_store

Learn how to integrate with a Shopify Hydrogen store, or with any headless Shopify store using a custom storefront

While this guide uses examples for Shopify's <a href="https://shopify.dev/custom-storefronts/hydrogen" target="_blank">Hydrogen framework</a>, the concepts and principles are true for any setup where you are using Shopify to power your ecommerce store’s backend, but have a custom storefront (a “headless” setup). This integration requires 2 main steps:

1. Connect your Shopify store via Klaviyo’s native integration to sync order, catalog, and subscriber data
2. Manually add code snippets to your site to enable onsite tracking functionality

> [!NOTE]
> **For free accounts**
> As discussed below, if you don't have redirect rules in place from the _myshopify.com_ domain to your hosted domain, or don't want shoppers to see the _myshopify.com_ domain in Klaviyo emails, you will need to contact Klaviyo's customer support team to update the product URLs that automatically sync through your catalog. If you are using Klaviyo's free plan, you have 60 days of dedicated email support after account creation during which you can submit a request. After the 60 day period, you must <a href="https://www.klaviyo.com/account?source=accountplan#create-your-plan-tab" target="_blank">upgrade your account</a> to submit further requests.

## Key integration components

The key components of integrating this type of ecommerce solution are:

- **Customer data**  
  Tracking information such as name, email, phone number, and other profile attributes
- **Subscribers**  
  Tracking who opts in and to what marketing channel (e.g., your email newsletter subscribers)
- **Order activity**  
  Tracking when a customer places an order, what products are ordered, etc.
- **Products**  
  The items in your catalog
- **Website activity**  
  Tracking who is active on your site, what products they view, etc.

With the exception of website activity, Klaviyo’s native Shopify integration will sync all of the above data for a headless Shopify store because this data is fetched server-side via API. 

Additionally, if you don't have redirect rules in place from the _myshopify.com_ domain to your hosted domain, or don't want shoppers to see the _myshopify.com_ domain in Klaviyo emails, you will need to request that Klaviyo support update the product URLs that automatically sync through your catalog. Read the [catalog section below](https://developers.klaviyo.com/en/docs/integrate_with_a_shopify_hydrogen_store.md) to learn more. 

## Connect Klaviyo’s native Shopify integration

The first step is to integrate your Shopify store via Klaviyo’s native integration. Follow the steps in our [Getting started with Shopify](https://help.klaviyo.com/hc/en-us/articles/115005080407) guide through step 14. Ignore the **Onsite Tracking** box and its status; you’ll add onsite tracking manually later.

## Enable onsite tracking

```prompt Add Klaviyo onsite tracking to this Hydrogen store
Add Klaviyo's onsite tracking (Active on Site, Viewed Product and Added to Cart) to this Shopify Hydrogen storefront.

First read https://developers.klaviyo.com/en/docs/integrate_with_a_shopify_hydrogen_store.md.

Ask me for these before you change anything, unless I've already given them:
- My Klaviyo public API key, from https://www.klaviyo.com/settings/account/api-keys. It's public, so it can go in the page; don't ask for or use a private key.
- Whether the store is already connected through Klaviyo's native Shopify integration. If it isn't, stop and point me to the guide's "Connect Klaviyo's native Shopify integration" section; that's done in Klaviyo and Shopify, not in code.

Then, following this storefront's language, framework and conventions:
1. In `root.jsx`, import `Script` from `@shopify/hydrogen` and add `<Script async type="text/javascript" src="//static.klaviyo.com/onsite/js/<public API key>/klaviyo.js" />` in the body. If Klaviyo.js is already loaded, don't add it twice.
2. Create an onsite module (the guide uses `app/components/Onsite.jsx`) that exports `trackViewedProduct(product)` and `trackAddedToCart(product)`. Each builds the item the guide shows (`Name`, `ProductID`, `ImageURL`, `Handle`, `Brand`, `Price`) and gets the klaviyo object through the guide's `getKlaviyo`, which runs Klaviyo's loading snippet first. Klaviyo.js loads asynchronously, and without the snippet a call made before it loads throws and the event is lost. `trackViewedProduct` also adds `Metadata` and calls `klaviyo.track('Hydrogen Viewed Product', item)` and `klaviyo.trackViewedItem(item)`; `trackAddedToCart` calls `klaviyo.track('Hydrogen Added To Cart', item)`. Map each field to the product data this storefront's loaders actually return.
3. In the product route (for example `app/routes/products.$handle.jsx`), call `trackViewedProduct` in a `useEffect` on page load, and call `trackAddedToCart` in the add-to-cart click handler without changing what the button already does.
4. If the storefront sets a content security policy, check whether it would block Klaviyo's script and tell me what needs changing.

Don't change the Shopify integration, Customer Privacy settings or catalog URLs; those are handled in Klaviyo, Shopify or by Klaviyo support.

When you're done, tell me what you changed and how to test it, ideally on an Oxygen preview build: view a product, add it to the cart, and look for the events in Klaviyo. Remind me that visitors in the EU, EEA, UK and Switzerland may not be tracked without consent.
```

For headless setups, you will need to manually install Klaviyo's “Active on Site” JavaScript (also known as Klaviyo.js). Klaviyo.js tracks when users are active on your site and enables Klaviyo forms.

If you want to track when users view specific products on your site (which can be leveraged in a browse abandonment flow), you’ll need to add Klaviyo’s _Viewed Product_ tracking JavaScript snippet. Below, we provide code snippets and guidance for tracking _Active on Site_, _Viewed Product_, and _Added to Cart_ events, which allow you to send cart abandonment flows.

> [!NOTE]
> Based on your Customer Privacy settings in Shopify, Klaviyo may not track onsite events (including _Active on Site_, _Viewed Product_, and _Added to Cart_) for visitors to your Shopify store in the EU, EEA, UK and Switzerland, unless they have provided consent. This does not affect logged-in user tracking.

### Add Active on Site tracking

With Hydrogen 2, you’ll want to include `import {Script} from '@shopify/hydrogen';` in `root.jsx` and add our standard onsite snippet within a `Script` element. Replace the placeholder value for the `PUBLIC_API_KEY` in the example below with your <a href="https://www.klaviyo.com/settings/account/api-keys" target="_blank">Klaviyo Public API key</a>.

```javascript
export default function App() {
  const nonce = useNonce();
  /** @type {LoaderReturnData} */
  const data = useLoaderData();

  return (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width,initial-scale=1" />
        <Meta />
        <Links />
      </head>
      <body>
        <Layout {...data}>
          <Outlet />
        </Layout>
        <Script async type="text/javascript"
  src="//static.klaviyo.com/onsite/js/PUBLIC_API_KEY/klaviyo.js" />
        <ScrollRestoration nonce={nonce} />
        <Scripts nonce={nonce} />
      </body>
    </html>
  );
}
```

### Add Viewed Product and Added to Cart tracking

To implement _Viewed Product_ and _Added to Cart_ tracking, we recommend first creating a component for our onsite tracking. In the example below, we create an Onsite component in `app/components/Onsite.jsx` and then add our standard _Viewed Product_ and _Added to Cart_ tracking requests.

Update the values of the JSON properties in the snippet so that they dynamically pull from the relevant information needed for that property.

The functions get the _klaviyo_ object through `getKlaviyo`, which runs Klaviyo's [loading snippet](https://developers.klaviyo.com/en/docs/introduction_to_the_klaviyo_object.md) first. Klaviyo.js loads asynchronously, so a product page can call `trackViewedProduct` before it has loaded; the snippet queues those calls until it does.

```javascript
// Klaviyo's loading snippet for the klaviyo object. It only runs if the object doesn't exist yet.
function getKlaviyo() {
  !function(){if(!window.klaviyo){window._klOnsite=window._klOnsite||[];try{window.klaviyo=new Proxy({},{get:function(n,i){return"push"===i?function(){var n;(n=window._klOnsite).push.apply(n,arguments)}:function(){for(var n=arguments.length,o=new Array(n),w=0;w<n;w++)o[w]=arguments[w];var t="function"==typeof o[o.length-1]?o.pop():void 0,e=new Promise((function(n){window._klOnsite.push([i].concat(o,[function(i){t&&t(i),n(i)}]))}));return e}}})}catch(n){window.klaviyo=window.klaviyo||[],window.klaviyo.push=function(){var n;(n=window._klOnsite).push.apply(n,arguments)}}}}();
  return window.klaviyo;
}

export function trackViewedProduct(product) {
  const klaviyo = getKlaviyo();
  const item = {
    Name: product.title,
    ProductID: product.id.substring(product.id.lastIndexOf('/') + 1),
    ImageURL: product.selectedVariant.image.url,
    Handle: product.handle,
    Brand: product.vendor,
    Price: product.selectedVariant.price.amount,
    Metadata: {
      Brand: product.vendor,
      Price: product.selectedVariant.unitPrice,
      CompareAtPrice: product.selectedVariant.compareAtPrice,
    },
  };
  klaviyo.track('Hydrogen Viewed Product', item);
  klaviyo.trackViewedItem(item);
}

export function trackAddedToCart(product) {
  const klaviyo = getKlaviyo();
  const item = {
    Name: product.title,
    ProductID: product.id.substring(product.id.lastIndexOf('/') + 1),
    ImageURL: product.selectedVariant.image.url,
    Handle: product.handle,
    Brand: product.vendor,
    Price: product.selectedVariant.price.amount,
  };
  klaviyo.track('Hydrogen Added To Cart', item);
}
```

You can now import those functions into your product file (for example, `app/routes/products.$handle.jsx`). Import the onsite functions and `useEffect` into your product file:

```javascript
import { useEffect } from "react";
import {trackViewedProduct, trackAddedToCart} from '~/components/Onsite';
```

Then, you can load `trackViewedProduct` on page load via `useEffect` within your `Product()` function. Here’s an example of how this would look within your `products.$handle.jsx` file:

```javascript
export default function Product() {
  /** @type {LoaderReturnData} */
  const {product, variants} = useLoaderData();
  const {selectedVariant} = product;

  // Execute VP on page load ***

  useEffect(() => {
    trackViewedProduct(product);
  },[]);


  return ( ...

```

For `trackAddedToCart`, you’ll want to invoke this within your added to cart click handler. Here’s an example snippet using the `ProductForm()` function:

```javascript
function ProductForm({product, selectedVariant, variants}) {

  // define atc ***
  const handleAtc = function () {
    trackAddedToCart(product)
  }

  return (
    <div className="product-form">
      <VariantSelector
        handle={product.handle}
        options={product.options}
        variants={variants}
      >
        {({option}) => <ProductOptions key={option.name} option={option} />}
      </VariantSelector>
      <br />
      <AddToCartButton
        disabled={!selectedVariant || !selectedVariant.availableForSale}
        onClick={() => {
          // Add our newly created click handler ***
          handleAtc();
          window.location.href = window.location.href + '#cart-aside';
        }}
        lines={
          selectedVariant
            ? [
                {
                  merchandiseId: selectedVariant.id,
                  quantity: 1,
                },
              ]
            : []
        }
      >
        {selectedVariant?.availableForSale ? 'Add to cart' : 'Sold out'}
      </AddToCartButton>
    </div>
  );
}
```

With our onsite scripts, forms should appear on local environments without any issues. However, content security policies can impact the functionality of our scripts both on local and production environments. We suggest testing through preview builds sent up to Shopify via Oxygen or custom deployments. If you encounter issues, you’ll need to configure your CSP to allow our JavaScript to function.

## Example code for onsite tracking

Klaviyo has provided reference code  to showcase how to <a href="https://github.com/klaviyo-labs/Hydrogen-2-Example/" target="_blank">implement the onsite tracking above</a>. You can also check out <a href="https://hydrogen2example-3ad64e75e88dc3df299c.o2.myshopify.dev/" target="_blank">the test store</a> that utilizes this reference code.

## Update your Shopify catalog URLs

Your Shopify catalog will sync with Klaviyo through the native integration, though the product catalog in Klaviyo will autopopulate with the _myshopify.com_ URL. <a href="https://help.klaviyo.com/hc/en-us/articles/115001002272-How-to-Contact-Support" target="_blank">Contact Klaviyo support</a> to request an update to this setting.

The URL can be updated from:  
`https://[INSTANCE].myshopify.com/products/[PRODUCT_HANDLE]`  
to:  
`https://[STOREFRONT_URL]/products/[PRODUCT_HANDLE]`

## Server-side and onsite metrics

Once you connect your store, the following metrics will sync through Klaviyo’s native Shopify integration:

- **Checkout Started**  
  When customers start a checkout and provide their contact information    
- **Placed Order**  
  When an order successfully processes on your system    
- **Ordered Product**  
  An event for each item in a processed order
- **Fulfilled Order**  
  When an order is sent to the customer
- **Fulfilled Partial Order**  
  When an order that has been placed is partially fulfilled
- **Canceled Order**  
  When an order is canceled
- **Refunded Order**  
  When a customer’s order is refunded

> [!NOTE]
> _Checkout Started_ events will sync only if customers enter contact and shipping information on the first page of the checkout process and click continue.

For more information about metrics synced from Shopify and their properties, check out our <a href="https://help.klaviyo.com/hc/en-us/articles/115005080447" target="_blank">Shopify data reference</a>. 

The following onsite metrics can be tracked in Klaviyo by manually adding the code snippets shared above to your site:

- **Active on Site**  
  When someone visits your website
- **Viewed Product**  
  When someone views a product 
- **Added to Cart**  
  When someone adds an item to their cart

## Additional resources

### Klaviyo resources

- <a href="https://help.klaviyo.com/hc/en-us/articles/115005080407-Guide-to-Integrating-with-Shopify" target="_blank">Getting started with Shopify</a>
- <a href="https://community.klaviyo.com/groups/developer-group-64" target="_blank">Developer Group on the Klaviyo Community</a>

### Shopify resources

- <a href="https://shopify.dev/custom-storefronts/hydrogen" target="_blank">Hydrogen overview for Developers</a>
- <a href="https://shopify.dev/api/storefront#development_frameworks_and_sdks" target="_blank">Shopify storefront API</a>
