npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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

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/pixel on 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:

  1. Install the PixelRelay app on your Shopify store and complete onboarding.
  2. Pick a plan that includes Hydrogen support.
  3. 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-route

The 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

  1. Enable debug logging: debug prop on the provider, or in the browser console: localStorage.setItem('pixelrelay:debug', '1') and reload.
  2. Navigate the storefront with DevTools → Network open — you should see POST /api/pixel with JSON bodies (status 204).
  3. Turn ON an ad blocker and repeat — events must still post to your origin.
  4. 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 |