@pixelrelay/hydrogen
v0.4.0
Published
Server-side conversion tracking for Hydrogen storefronts — adblock-resilient Meta CAPI, GA4, TikTok, Google Ads, and more via PixelRelay
Downloads
146
Maintainers
Readme
@pixelrelay/hydrogen
Server-side conversion tracking for Hydrogen storefronts.
Shopify's native channel apps (Google & YouTube, Facebook & Instagram, TikTok) inject their pixels through the Online Store theme — none of that runs on a headless storefront. This package restores full-funnel, adblock-resilient tracking for Hydrogen: events flow first-party from your own domain to the PixelRelay relay, which forwards them server-side to Meta CAPI, GA4, Google Ads, TikTok, Snapchat, Pinterest, Microsoft/Bing, Reddit, LinkedIn, Klaviyo, and Segment — deduplicated against your Shopify order webhooks.
- Adblock-resilient by architecture — events POST to
/api/pixelon your own origin; your server forwards them. When Hydrogen's analytics bus is stalled by a blocker, a built-in fallback keeps page views flowing. - Native Hydrogen integration — subscribes to
<Analytics.Provider>'s event bus; page views, product views, and cart events flow automatically. - Purchase attribution that survives checkout — click IDs (fbclid→fbc, gclid, gbraid/wbraid, ttclid, msclkid, ScCid, epik, rdt_cid, li_fat_id) are captured from landing URLs, persisted first-party, and stamped onto the Shopify cart so the order webhook carries them even when the buyer's browser never talks to an ad platform.
- Consent-aware — reads Shopify's Customer Privacy API and forwards the shopper's actual choices; the relay strips PII per-signal accordingly.
Prerequisites (Step 0)
Before touching code you need a PIXEL_RELAY_SECRET:
- Install the PixelRelay app on your Shopify store and complete onboarding.
- Pick a plan that includes Hydrogen support.
- Open Settings → Hydrogen Setup in the PixelRelay dashboard and copy the per-shop token.
Without the token, events are rejected (401); on a plan without Hydrogen
support you'll see 402.
Install
npm install @pixelrelay/hydrogen
npx pixelrelay-hydrogen install-routeThe installer copies app/routes/api.pixel.tsx (the first-party proxy route),
appends PIXEL_RELAY_SECRET= to your .env, and warns if your routes.ts
wouldn't register the file. Paste your token into .env and add the same
variable to your Oxygen (or other host) environment settings.
The relay URL ships inside the package — you do not configure it. Set the
optional PIXEL_RELAY_URL only for self-hosted/staging relays.
Wire up root.tsx
This is the full pattern from a working React Router 7 Hydrogen skeleton —
note the cart stays deferred (no await context.cart.get() blocking the
root loader); <PixelRelayCartAttributes> handles the cart write inside
<Await>:
import { Suspense } from 'react';
import { Await, Outlet, useRouteLoaderData } from 'react-router';
import { Analytics } from '@shopify/hydrogen';
import { PixelRelayProvider, PixelRelayCartAttributes } from '@pixelrelay/hydrogen';
const STOREFRONT_API_VERSION = '2025-10';
export default function App() {
const data = useRouteLoaderData<RootLoader>('root');
if (!data) return <Outlet />;
const storefrontApiUrl =
`https://${data.publicStoreDomain}/api/${STOREFRONT_API_VERSION}/graphql.json`;
return (
<Analytics.Provider cart={data.cart} shop={data.shop} consent={data.consent}>
<PixelRelayProvider
shop={data.publicStoreDomain}
storefrontApiUrl={storefrontApiUrl}
storefrontToken={data.consent.storefrontAccessToken}
>
<Suspense fallback={<PageLayout {...data}><Outlet /></PageLayout>}>
<Await resolve={data.cart}>
{(cart) => (
<>
<PixelRelayCartAttributes
cartId={cart?.id}
storefrontApiUrl={storefrontApiUrl}
storefrontToken={data.consent.storefrontAccessToken}
/>
<PageLayout {...data}>
<Outlet />
</PageLayout>
</>
)}
</Await>
</Suspense>
</PixelRelayProvider>
</Analytics.Provider>
);
}publicStoreDomain, shop, and consent are what the Hydrogen skeleton's
root loader already returns (PUBLIC_STORE_DOMAIN, getShopAnalytics(...),
and the consent block with storefrontAccessToken). No extra loader work is
needed.
Page views are automatic. Once the provider is mounted, page_viewed
fires on every route change — from Hydrogen's analytics bus when it's alive,
or from a built-in useLocation fallback when the bus is absent or stalled
(the usual cause: an ad blocker blocking shopify-perf-kit, which Hydrogen
waits on before publishing any bus event).
Per-route view events
Product, collection, search, and cart views use Hydrogen's own marker components — render them where Hydrogen's docs say to:
// products.$handle.tsx → <Analytics.ProductView data={{products: [...]}} />
// collections.$handle.tsx → <Analytics.CollectionView data={{collection}} />
// search.tsx → <Analytics.SearchView data={{searchTerm, searchResults}} />
// cart.tsx → <Analytics.CartView />PixelRelay picks each one up from the bus automatically.
Add to cart (recommended: explicit, adblock-resilient)
Hydrogen's bus PRODUCT_ADD_TO_CART event never fires for blocker-stalled
visitors. Wire useTrackAddToCart() into your Add-to-cart button — it posts
through the same first-party proxy, so it works for everyone, and it
auto-suppresses the bus event so unblocked visitors aren't double-counted:
import { useTrackAddToCart } from '@pixelrelay/hydrogen';
export function ProductForm({ selectedVariant }) {
const trackAddToCart = useTrackAddToCart();
return (
<AddToCartButton
lines={[{ merchandiseId: selectedVariant.id, quantity: 1 }]}
onClick={() => trackAddToCart(selectedVariant, 1)}
>
Add to cart
</AddToCartButton>
);
}Purchases
You don't track purchases in the browser. Checkout happens on
checkout.shopify.com; the PixelRelay Shopify app receives the orders/paid
webhook and relays the purchase server-side with the click IDs and durable ID
this package stamped onto the cart. Everything is deduplicated by a shared
event ID, so nothing is counted twice.
Verify it works
- Enable debug logging:
debugprop on the provider, or in the browser console:localStorage.setItem('pixelrelay:debug', '1')and reload. - Navigate the storefront with DevTools → Network open — you should see
POST /api/pixelwith JSON bodies (status 204). - Turn ON an ad blocker and repeat — events must still post to your origin.
- Check the PixelRelay dashboard → your store → recent events.
Troubleshooting: 401 = wrong/missing PIXEL_RELAY_SECRET; 402 = your
plan doesn't include Hydrogen support; no requests at all = the route isn't
registered (check routes.ts uses flatRoutes() or add
route('/api/pixel', 'routes/api.pixel.tsx')).
Server-side events (loaders / actions)
import { relayEvent, extractCartSignals } from '@pixelrelay/hydrogen/server';
export async function action({ request, context }) {
await relayEvent({
shop: context.env.PUBLIC_STORE_DOMAIN,
eventName: 'product_added_to_cart',
payload: { cartLine: { merchandise: { id, product, price }, quantity: 1 } },
relaySecret: context.env.PIXEL_RELAY_SECRET,
clientIpAddress: request.headers.get('x-forwarded-for')?.split(',')[0],
cart: cartData, // optional: recovers _relay_* attribution from cart attributes
});
}Network errors return { ok: false, status: 0 } and never throw.
API
<PixelRelayProvider>
| Prop | Type | Required | Description |
|------|------|----------|-------------|
| shop | string | yes | Myshopify domain, e.g. "store.myshopify.com" |
| proxyUrl | string | no | First-party POST URL for track(). Default: /api/pixel |
| storefrontApiUrl | string | no | Storefront GraphQL endpoint — needed for cart-attribute writes |
| storefrontToken | string | no | Public Storefront token — needed for cart-attribute writes |
| cartId | string | no | Cart GID. Prefer <PixelRelayCartAttributes> with a deferred cart instead |
| scripts | PixelScriptConfig | no | Optional browser pixel IDs to inject (Meta/TikTok/GA4/Snap/Bing tags) |
| debug | boolean | no | Verbose console logging (also: localStorage.setItem('pixelrelay:debug','1')) |
| endpoint | string | no | Deprecated — alias for proxyUrl |
<PixelRelayCartAttributes>
Renders nothing. Stamps attribution (_relay_* click IDs, durable ID, GA
session) onto the Shopify cart via cartAttributesUpdate so the order
webhook can recover it. Mount inside <Await resolve={cart}> when the cart
is deferred (recommended — see the root.tsx example). Reads the cart's
existing attributes first and writes the merged set, so merchant-set
attributes (gift notes etc.) are preserved; re-syncs when signals change.
Props: cartId, storefrontApiUrl, storefrontToken.
useTrackEvent() → track(eventName, payload?)
Client hook for custom events. For purchase-class events you must pass
payload.orderId — purchases without an order ID are dropped by the relay
(the order webhook is the authoritative purchase sender).
useTrackAddToCart() → trackAddToCart(variant, quantity?)
Client hook; variant is a Storefront API variant ({ id, price, product? }),
quantity defaults to 1. Auto-suppresses the analytics-bus add-to-cart.
buildAddToCartPayload(variant, quantity?)
Pure helper building the { cartLine } payload useTrackAddToCart sends.
relayEvent(options) / extractCartSignals(cart) / relayPixelEndpoint(override?) (from /server)
Server-side relay POST; cart-attribute → body signal extraction; relay
endpoint resolution (built-in default, PIXEL_RELAY_URL override).
Event coverage
| Event | Source | Automatic? |
|-------|--------|------------|
| page_viewed | bus, or useLocation fallback | yes |
| product_viewed | bus + <Analytics.ProductView> | yes (with marker) |
| collection_viewed | bus + <Analytics.CollectionView> | yes (with marker) |
| search_submitted | bus + <Analytics.SearchView> | yes (with marker) |
| cart_viewed | bus + <Analytics.CartView> | yes (with marker) |
| product_added_to_cart | useTrackAddToCart() (recommended) or bus | yes |
| checkout_started | Shopify checkout (Web Pixel) | yes — no storefront code |
| Purchase | orders/paid webhook + cart attributes | yes — no storefront code |
