# Instrument a Shopify Hydrogen storefront with Sentry

> Add Sentry to a Shopify Hydrogen storefront on Oxygen. Trace Storefront API queries, catch silent cart errors, and alert when add-to-cart starts failing.

**URL:** https://sentry.io/cookbook/instrument-shopify-hydrogen-storefront/

---

A headless storefront splits every page across the browser, the Oxygen worker, and Shopify's Storefront API. Trace all three, give every Storefront API query a name you can search, and catch the cart errors that never throw an exception.

**Time:** 25-30 minutes | **Difficulty:** Intermediate

## What You'll Learn

- Added Sentry to the browser and the Oxygen worker

- Connected server and browser traces and allowed Sentry in Hydrogen's CSP

- Uploaded source maps for readable stack traces

- Named every Storefront API query with a span

- Recorded cart errors that never throw an exception

- Built a storefront dashboard and alerts for cart failures

**Topics:** Error Monitoring, Tracing, Session Replay, Logs, Metrics, Alerts

**SDKs:** React Router, Hydrogen

## Before you start

**SDKs & packages**

- A Hydrogen storefront on version `2026.4.3` through `2026.4.x` (React Router 7.15 or later)

- [@sentry/react-router and @sentry/cloudflare](https://docs.sentry.io/platforms/javascript/guides/cloudflare/frameworks/hydrogen-react-router/) `11.0.0` or later (logs and metrics are on by default)

- The [Sentry CLI](https://cli.sentry.dev/) (`npx sentry@latest`) for source maps and dashboards

**Accounts & access**

- [Sentry account](https://sentry.io/signup/) with a project for the storefront

- A Shopify store with Hydrogen deployed to Oxygen

- A Sentry auth token for uploading source maps

**Knowledge**

- Familiarity with React Router loaders and actions

- A basic understanding of the Storefront API and Hydrogen's cart

## Steps

### 1. Add Sentry to the browser and the Oxygen worker

In a Hydrogen storefront, a slow product page can be caused by the browser, your Oxygen worker, or the Storefront API, and each layer reports to a different place. Start by installing the React Router and Cloudflare SDKs. Oxygen runs on a Workers-style runtime, so the server side uses the Cloudflare SDK's request wrapper.

Initialize Sentry in the browser with tracing and Replay (logs are on by default), and pass `Sentry.sentryOnError` to the router so client-side errors are reported. On the server, wrap Hydrogen's request handler in `server.ts` and read the DSN from Oxygen's environment variables. Add `SENTRY_DSN` to the `Env` type in `env.d.ts` and to your Oxygen environment variables.

On Oxygen, import only `@sentry/cloudflare/request` from the Cloudflare package. Any other import from it breaks the app. Use `@sentry/react-router/cloudflare` for everything else. **Using Next.js or another framework with the Storefront API?** Set up that framework's Sentry SDK in place of steps 1 and 2. Steps 3 through 6 work the same way.

**Install**

```bash
npm install @sentry/react-router @sentry/cloudflare
```

**entry.client.tsx**

```typescript
import { HydratedRouter } from "react-router/dom";
import * as Sentry from "@sentry/react-router/cloudflare";
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.us.sentry.io/0",
  integrations: [Sentry.reactRouterTracingIntegration(), Sentry.replayIntegration()],
  tracesSampleRate: 0.2,
  replaysSessionSampleRate: 0.05,
  replaysOnErrorSampleRate: 1.0,
});

startTransition(() => {
  hydrateRoot(document, <StrictMode><HydratedRouter onError={Sentry.sentryOnError} /></StrictMode>);
});
```

**server.ts**

```typescript
import { wrapRequestHandler } from "@sentry/cloudflare/request"; // the only @sentry/cloudflare import allowed

export default {
  async fetch(request: Request, env: Env, executionContext: ExecutionContext) {
    return wrapRequestHandler(
      {
        options: { dsn: env.SENTRY_DSN, tracesSampleRate: 0.2 },
        request: request as any,
        context: executionContext,
      },
      async () => {
        // move your existing fetch body here and return its Response
      },
    );
  },
};
```

[Hydrogen with React Router setup guide](https://docs.sentry.io/platforms/javascript/guides/cloudflare/frameworks/hydrogen-react-router/)

### 2. Connect the traces and allow Sentry in your CSP

Update `entry.server.tsx` to do three things: inject trace meta tags so the browser's pageload continues the server's trace, report server render errors with `handleError`, and add Sentry to Hydrogen's Content Security Policy. Hydrogen ships a strict CSP by default, and without this change the browser silently blocks every request to Sentry.

Then upload source maps so stack traces show your code instead of the minified worker bundle. Add `sentryReactRouter` to the plugins in `vite.config.ts` and call `sentryOnBuildEnd` from the `buildEnd` hook in `react-router.config.ts`. Set `build.sourcemap` to `"hidden"` so the build emits `.map` files without linking them in your bundles. The plugin injects debug IDs and uploads the maps at the end of `shopify hydrogen build`, then deletes the `.map` files. Set `SENTRY_AUTH_TOKEN` in the environment of the build, for example in your CI job.

**entry.server.tsx**

```typescript
import "./instrument.server"; // Sentry.init for the server, per the setup guide
import * as Sentry from "@sentry/react-router/cloudflare";
import { ServerRouter, type EntryContext, type HandleErrorFunction } from "react-router";
import { isbot } from "isbot";
import { renderToReadableStream } from "react-dom/server";
import { createContentSecurityPolicy, type HydrogenRouterContextProvider } from "@shopify/hydrogen";

async function handleRequest(
  request: Request,
  responseStatusCode: number,
  responseHeaders: Headers,
  reactRouterContext: EntryContext,
  context: HydrogenRouterContextProvider,
) {
  const { nonce, header, NonceProvider } = createContentSecurityPolicy({
    shop: {
      checkoutDomain: context.env.PUBLIC_CHECKOUT_DOMAIN,
      storeDomain: context.env.PUBLIC_STORE_DOMAIN,
    },
    connectSrc: ["https://*.ingest.us.sentry.io"], // match the host in your DSN
    workerSrc: ["blob:"],                          // Session Replay's compression worker
  });

  const stream = await renderToReadableStream(
    <NonceProvider><ServerRouter context={reactRouterContext} url={request.url} nonce={nonce} /></NonceProvider>,
    {
      nonce,
      signal: request.signal,
      onError(error) {
        console.error(error);
        responseStatusCode = 500;
      },
    },
  );

  if (isbot(request.headers.get("user-agent"))) await stream.allReady;

  const body = Sentry.injectTraceMetaTags(stream);

  responseHeaders.set("Content-Type", "text/html");
  responseHeaders.set("Content-Security-Policy", header);
  return new Response(body, { headers: responseHeaders, status: responseStatusCode });
}

export const handleError: HandleErrorFunction = (error, { request }) => {
  if (!request.signal.aborted) Sentry.captureException(error);
};

export default Sentry.wrapSentryHandleRequest(handleRequest);
```

**vite.config.ts**

```typescript
import { sentryReactRouter } from "@sentry/react-router/vite";

const sentryConfig = {
  org: "example-org",
  project: "example-project",
  authToken: process.env.SENTRY_AUTH_TOKEN,
};

export default defineConfig((config) => ({
  plugins: [
    hydrogen(),
    oxygen(),
    reactRouter(),
    sentryReactRouter(sentryConfig, config),
    tsconfigPaths(),
  ],
  build: {
    sourcemap: "hidden",
  },
}));
```

**react-router.config.ts**

```typescript
import type { Config } from "@react-router/dev/config";
import { sentryOnBuildEnd } from "@sentry/react-router/vite";

export default {
  appDirectory: "app",
  buildDirectory: "dist",
  ssr: true,
  buildEnd: async ({ viteConfig, reactRouterConfig, buildManifest }) => {
    await sentryOnBuildEnd({ viteConfig, reactRouterConfig, buildManifest });
  },
} satisfies Config;
```

[Source maps for Hydrogen](https://docs.sentry.io/platforms/javascript/guides/cloudflare/frameworks/hydrogen-react-router/#add-readable-stack-traces-with-source-maps-optional)

### 3. Give every Storefront API query a name

Every Storefront API request is a `POST` to the same GraphQL endpoint, so the automatic network spans all look alike. Wrap the existing `storefront.query` call inside `loadCriticalData` in a span named after the query. Now you can find your slowest queries by name and see which ones a slow page is waiting on.

While you're in the loader, log missing products instead of only returning a 404. A spike in `storefront.product_not_found` usually means a product was unpublished or a marketing link is broken. Use the same span name as your GraphQL operation (`ProductQuery`, `CollectionQuery`) so traces match the queries in your code.

```typescript
import * as Sentry from "@sentry/react-router/cloudflare";
import { getSelectedProductOptions } from "@shopify/hydrogen";
import type { Route } from "./+types/products.$handle";

async function loadCriticalData({ context, params, request }: Route.LoaderArgs) {
  const { handle } = params;

  const { product } = await Sentry.startSpan(
    { name: "ProductQuery", op: "storefront.query", attributes: { "product.handle": handle } },
    () =>
      context.storefront.query(PRODUCT_QUERY, {
        variables: { handle, selectedOptions: getSelectedProductOptions(request) },
      }),
  );

  if (!product?.id) {
    Sentry.logger.warn("storefront.product_not_found", { "product.handle": handle });
    throw new Response(null, { status: 404 });
  }

  return { product };
}
```

[Custom spans](https://docs.sentry.io/platforms/javascript/guides/cloudflare/tracing/instrumentation/)

### 4. Catch cart errors that never raise an exception

Hydrogen's cart methods return `{ cart, userErrors, warnings, errors }` instead of throwing. `userErrors` holds the Storefront API's cart user errors, like an invalid quantity. `warnings` holds stock and discount problems: out-of-stock variants, not enough stock, and discount codes that don't exist. `errors` holds only top-level GraphQL errors. In the skeleton template, the cart action passes all of these straight back to the page, and your monitoring never hears about them.

Add a few lines after the `switch` in `app/routes/cart.tsx` to count every cart mutation by outcome and log the details of each failure. These are logs and metrics, not exceptions. An out-of-stock warning is expected behavior for one shopper, but a jump in `cart.mutation_failed` across all shoppers points to a problem, like an inventory sync failure or a bad deploy.

```typescript
import * as Sentry from "@sentry/react-router/cloudflare";

const { cart: cartResult, userErrors, warnings, errors } = result;

const outcome = errors?.length ? "api_error" : userErrors?.length ? "user_error" : warnings?.length ? "warning" : "success";
Sentry.metrics.count("cart.mutation", 1, { attributes: { "cart.action": action, result: outcome } });

if (outcome !== "success") {
  const detail = userErrors?.[0] ?? warnings?.[0];
  Sentry.logger.warn("cart.mutation_failed", {
    "cart.action": action,
    "error.code": detail?.code ?? "unknown",
    "error.message": detail?.message ?? errors?.[0]?.message,
    "cart.id": cartId ?? "none",
  });
}
```

[Set up logs](https://docs.sentry.io/platforms/javascript/guides/cloudflare/logs/)

### 5. Follow a slow page from browser to Storefront API

Deploy, browse a few pages, and add something to your cart. Then open the [Trace Explorer](https://sentry.io/orgredirect/organizations/:orgslug/explore/traces/) and filter to `span.op:storefront.query`.

Group by `span.description` and sort by p95 duration to find your slowest queries. Open any trace to see one page load end to end: the browser pageload, the request to your Oxygen worker, the loader, and each named Storefront API query inside it. If a query is slow on every request, check whether its loader sets a Hydrogen cache strategy like `CacheShort()` or `CacheLong()`.

For cart problems, filter the [Logs Explorer](https://sentry.io/orgredirect/organizations/:orgslug/explore/logs/) to `message:cart.mutation_failed` and group by `error.code`. From any log, jump to its trace and the shopper's Session Replay to see what they tried to add and what the page showed them.

[Trace Explorer documentation](https://docs.sentry.io/product/explore/trace-explorer/)

### 6. Build a storefront dashboard and alerts

Save the queries you just ran as widgets on a storefront dashboard in [Dashboards](https://sentry.io/orgredirect/organizations/:orgslug/dashboards/), or create it from the terminal with the [Sentry CLI](https://cli.sentry.dev/). Add the **Cart mutations** metric widget in the Dashboards UI.

Then add two monitors. A threshold alert on `cart.mutation` where `result:warning` or `result:user_error` rises above your normal rate catches inventory and pricing problems. An anomaly alert on successful `cart.mutation` volume catches add-to-cart breaking outright, including failures that happen before the request leaves the browser.

- **Storefront API latency**: p95 duration of `span.op:storefront.query`, grouped by query name

- **Cart mutations**: `cart.mutation`, sum, grouped by `cart.action` and `result`

- **Cart errors**: count of `cart.mutation_failed` logs, grouped by `error.code`

- **Missing products**: count of `storefront.product_not_found` logs, grouped by `product.handle`

```bash
npx sentry@latest dashboard create Storefront
npx sentry@latest dashboard widget add Storefront "Storefront API latency" \
  --display line --query p95:span.duration \
  --where "span.op:storefront.query" --group-by span.description
npx sentry@latest dashboard widget add Storefront "Cart errors" \
  --dataset logs --display bar --query count \
  --where "message:cart.mutation_failed" --group-by error.code
npx sentry@latest dashboard widget add Storefront "Missing products" \
  --dataset logs --display bar --query count \
  --where "message:storefront.product_not_found" --group-by product.handle
```

[Alerts documentation](https://docs.sentry.io/product/monitors-and-alerts/alerts/)

## Summary

**Your whole storefront reports to one place.**

The browser, the Oxygen worker, and the Storefront API now share one trace. Every query has a name, and cart errors that used to disappear now show up as logs, metrics, and alerts.

## Pro Tips

- Lower `tracesSampleRate` for busy storefronts, but keep `replaysOnErrorSampleRate` at `1.0` so every errored session has a replay.

- Add `cart.id` to cart logs. It lets you follow one shopper's cart across add, update, and checkout.

- Set a release in your Sentry config and your CI build so new errors and slow queries line up with the deploy that caused them.

- Session Replay masks text and inputs by default, so shopper names and addresses stay out of recordings.

## Common Pitfalls

- Importing from `@sentry/cloudflare` directly. On Oxygen, only `@sentry/cloudflare/request` works.

- Skipping the CSP change. Hydrogen's default policy blocks requests to Sentry, and the only sign is a console warning in the shopper's browser.

- Skipping `build.sourcemap: "hidden"` or `SENTRY_AUTH_TOKEN`. Without them the build emits no source maps, or can't upload them, and stack traces stay minified.

- Capturing every cart user error as an exception. They're expected per shopper and will flood Issues. Use logs and metrics, and alert on the rate.

## FAQ

**Does this work with older Hydrogen versions on Remix?**

Yes, with different setup. Hydrogen versions before `2025.5.0` use Remix v2. Follow Sentry's Hydrogen with Remix guide for steps 1 and 2, then use steps 3 through 6 as written.

**Does this work with Hydrogen 2026.10?**

Not as written. Hydrogen 2026.10 removed the classic cart handler, `storefront.query`, and the CSP helper this recipe uses. Follow Shopify's 2026.10 migration and Sentry's React Router guide instead. Storefronts on Hydrogen `2025.5.0` through `2026.4.2` must upgrade React Router to 7.15 or later before they can use SDK v11.

**What about a headless storefront built with Next.js?**

Set up Sentry with the Next.js SDK, then wrap your Storefront API calls in named spans and check cart mutation responses for `userErrors`, as in steps 3 and 4. The Storefront API reports cart errors the same way no matter which framework calls it.

**Why not rely on the automatic fetch spans for Storefront API calls?**

They're useful for timing, but every Storefront API call has the same URL and method. Without a name, you can't tell which query was slow. A named span costs one line per query.

**Will this slow down my storefront?**

The SDK adds a small amount of JavaScript to the browser bundle, and spans and logs are sent in the background. Use the sample rates to control how much data each visit sends.

## Next Steps

- [Send Shopify Hydrogen trace exports to Sentry](/cookbook/send-shopify-hydrogen-traces-to-sentry/): Connect a Shopify observability drain to Sentry with no code changes.

- [Structure your logs](/cookbook/structure-your-logs/): Make every log queryable with stable event names and flat attributes.

- [Metrics dashboards and alerts](/cookbook/custom-metrics-dashboard-alerts-nextjs/): Go deeper on thresholds versus anomaly detection for custom metrics.

- [product/session-replay](https://sentry.io/product/session-replay/)

---

*Source: [sentry.io/cookbook/instrument-shopify-hydrogen-storefront/](https://sentry.io/cookbook/instrument-shopify-hydrogen-storefront/)*
