← Back to Cookbook

Instrument a Shopify Hydrogen storefront with Sentry

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.

Features
Category Monitoring
Time
25-30 minutes
Complexity
Intermediate
Steps
6 steps

Before you start

SDKs & packages
Accounts & access
  • Sentry account 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

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.

Hydrogen with React Router setup guide
Bash
npm install @sentry/react-router @sentry/cloudflare

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.

Source maps for Hydrogen
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);

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.

Custom spans
app/routes/products.$handle.tsx
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 };
}

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.

Set up logs
app/routes/cart.tsx
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",
  });
}

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 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 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

6
Build a storefront dashboard and alerts

Save the queries you just ran as widgets on a storefront dashboard in Dashboards, or create it from the terminal with the Sentry CLI. 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
Alerts documentation
Create the dashboard with the Sentry CLI
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

That's it.

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.

  • 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

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.

Frequently asked questions

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.

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.

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.

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.

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.

Fix it, don't observe it.

Get started with the only application monitoring platform that empowers developers to fix application problems without compromising on velocity.