Documentation menuEcommerce: Shopify Hydrogen

Ecommerce

Add Loogika to Shopify Hydrogen

In a Shopify Hydrogen storefront you add the Loogika tag to the head of the Layout component in app/root.tsx. The Content Security Policy is built in app/entry.server.tsx, and it must allow the Loogika host as well. Headless Hydrogen storefronts are the subject of this page, and the Shopify guide covers an Online Store theme.

Last updated .

What do you need before you start?

You need your site ID from Site Settings in Loogika, under the Tracking Script tab. The tag shown there contains the ID, a 12-character string. The examples on this page use YOUR_SITE_ID in its place.

How do you add the Loogika tag to Hydrogen?

Use the Script component from Hydrogen in app/root.tsx. Hydrogen ships with a Content Security Policy (CSP) based on a nonce, a one-time code that marks a script as allowed. The browser blocks an ordinary script tag that lacks the nonce, and the Script component adds the nonce for you.

import { Analytics, getShopAnalytics, Script, useNonce } from "@shopify/hydrogen";

export function Layout({children}: {children?: React.ReactNode}) {
  const nonce = useNonce();

  return (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width,initial-scale=1" />
        <Meta />
        <Links />
        <Script src="https://app.loogika.com/api/script.js?siteId=YOUR_SITE_ID" defer />
      </head>
      <body>
        {children}
        <ScrollRestoration nonce={nonce} />
        <Scripts nonce={nonce} />
      </body>
    </html>
  );
}

Hydrogen later moved to React Router. A project older than that move takes Meta, Links and Scripts from the @remix-run/react package, and the edit itself does not change.

What do you add to the Content Security Policy?

Add https://app.loogika.com to both scriptSrc and connectSrc in app/entry.server.tsx:

const {nonce, header, NonceProvider} = createContentSecurityPolicy({
  shop: {
    checkoutDomain: context.env.PUBLIC_CHECKOUT_DOMAIN,
    storeDomain: context.env.PUBLIC_STORE_DOMAIN,
  },
  scriptSrc: ["'self'", "https://cdn.shopify.com", "https://app.loogika.com"],
  connectSrc: ["https://app.loogika.com"],
});

Hydrogen merges the values you pass for connectSrc with its own defaults. The scriptSrc list has no default to merge with, so it must also name the Shopify CDN.

The connect-src entry lets the script send events to Loogika. The script-src entry is needed because session replay loads a second script from the same host while the page runs. Restart the dev server after the change.

Does Loogika track route changes in Hydrogen?

Yes. Loogika records a pageview when a visitor moves between routes without a full page load. SPA Navigation in Site Settings controls that behaviour, and it is on for a new site.

How do you track product views and add to cart in Hydrogen?

Subscribe to the storefront events that Hydrogen already publishes. The Analytics.Provider component sends out events such as product_viewed, product_added_to_cart and cart_updated. One small component can pass them on to Loogika, so you do not add tracking code to each route.

Create the file app/components/LoogikaAnalytics.tsx:

import { useAnalytics } from "@shopify/hydrogen";
import { useEffect } from "react";

declare global {
  interface Window {
    loogika?: {
      event: (name: string, properties?: Record<string, unknown>) => void;
    };
  }
}

export function LoogikaAnalytics() {
  const {subscribe, register} = useAnalytics();
  const {ready} = register("Loogika");

  useEffect(() => {
    subscribe("product_viewed", (data) => {
      const product = data.products[0];
      if (!product) return;
      window.loogika?.event("view_item", {
        item_id: product.sku || product.variantId,
        item_name: product.title,
        item_variant: product.variantTitle,
        price: Number(product.price),
      });
    });
    subscribe("product_added_to_cart", (data) => {
      const line = data.currentLine;
      if (!line) return;
      window.loogika?.event("add_to_cart", {
        item_id: line.merchandise.sku || line.merchandise.id,
        item_name: line.merchandise.product.title,
        price: Number(line.cost.totalAmount.amount),
        currency: line.cost.totalAmount.currencyCode,
        quantity: line.quantity,
      });
    });
    ready();
  }, []);

  return null;
}

The App component in app/root.tsx holds <Analytics.Provider>. Render <LoogikaAnalytics /> inside that provider. The declare global block tells TypeScript that window.loogika exists. Leave out the page_viewed event, because Loogika records route changes itself.

The deferred Loogika script may not have run yet when a subscription fires during the first page load. The ?. in the calls skips those early events without an error.

How do you track purchases from a Hydrogen storefront?

Use the custom pixel from the Shopify guide. The checkout does not run inside Hydrogen, so code in your storefront never sees the completed order. The pixel works the same way for Hydrogen and Online Store checkouts.

How do you check that Loogika is installed?

Visit the storefront in another browser tab and open a few products. The pageviews show up in the Loogika dashboard within a few seconds. If nothing arrives, open the browser console and look for the errors in the table below.

Why does Hydrogen not send data to Loogika?

SymptomCause and fix
The console says Refused to load the scriptEither entry.server.tsx lacks the CSP change or the dev server still runs without a restart. Session replay loads a second script, and the nonce does not cover that one
Requests to /api/track are blockedThe connectSrc list does not include https://app.loogika.com