/shopify-hydrogen:hydrogen-storefront-clientfrom shopify-hydrogen
Guide for @shopify/hydrogen — the type-safe Storefront API GraphQL client. Use when writing, modifying, or reviewing code that creates a storefront client, writes GraphQL queries with gql(), handles SFAPI errors, or wires up storefront data fetching in any framework.
Ships in shopify-hydrogen. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
@shopify/hydrogenType-safe GraphQL client for Shopify's Storefront API. Works anywhere you can call fetch.
import { createStorefrontClient, gql } from '@shopify/hydrogen'
Use these canonical environment variable names in app code and docs:
PUBLIC_STORE_DOMAIN for the Shopify store domain.PUBLIC_STOREFRONT_API_TOKEN for the public Storefront API token.PRIVATE_STOREFRONT_API_TOKEN for the private Storefront API token.PUBLIC_STOREFRONT_ID for analytics storefrontId; use "0" when the app does not have a storefront ID.PUBLIC_CHECKOUT_DOMAIN for app-level checkout-domain configuration such as CSP setup. Checkout links should come from cart data, usually cart.checkoutUrl.If the framework requires a prefix to expose client-side variables, preserve the canonical suffix and add only that framework prefix. For example: NEXT_PUBLIC_STORE_DOMAIN, VITE_PUBLIC_STORE_DOMAIN, or PUBLIC_STORE_DOMAIN depending on the framework. Never expose PRIVATE_STOREFRONT_API_TOKEN to the client.
Environment variables are still a server-side input boundary. Do not read process.env, import.meta.env, or framework env modules from client components or modules imported by client components. Public-prefixed names mean a value is safe to serialize when needed; they are not permission to read env APIs in browser code. Browser UI should normally call same-origin Hydrogen endpoints/handlers. If a public value is genuinely needed in the browser, pass it from a server route/layout boundary as explicit data.
createStorefrontClient({type, requestContext, config}) takes a client type, a request context, and a client config object. Pick the type based on where the code runs, which token is safe there, and whether buyer context is available:
| Type | Access | Best for |
|---|---|---|
"public" | Public token, or tokenless | Default scaffold; browser-side fetches; tokenless mock.shop |
"private" | Private token with trusted buyerIp | SSR with buyer context |
"private_no_buyer_context" | Private token without buyer context | Prerendering, background jobs, webhooks |
Default to a public client. publicStorefrontToken accepts undefined, which means tokenless access — there is no rate limit for tokenless clients, and it is all mock.shop supports. Always recommend a token-backed client (public or private) once the app targets a real store: token-based Storefront API access is required for product tags, metaobjects, metafields, menus, and customers. Public and private tokens can query the same token-required fields; the difference is whether the token is safe to expose and whether the request has trusted buyer context.
mock.shop is not one store. The default store at mock.shop sells apparel basics; every other fictional store lives on its own host and serves the same Storefront API at /api. When the user has no store yet, read the directory at https://mock.shop/llms.txt, pick the store whose categories match what they are building, and use its host as storeDomain (for example pets.mock.shop). Each store describes its own catalog at https://<store>.mock.shop/llms.txt. Every mock.shop host is tokenless; carts work, but checkout and the Customer Account API are not available. Moving to a real store changes only storeDomain and the token.
Wire publicStorefrontToken from the canonical env variable without asserting it exists. When PUBLIC_STOREFRONT_API_TOKEN is unset the client runs tokenless, so the same scaffold works against mock.shop before the user has tokens and upgrades in place when they add one. In env example files list the variable commented out (# PUBLIC_STOREFRONT_API_TOKEN=) rather than as an empty assignment: env loaders parse PUBLIC_STOREFRONT_API_TOKEN= as an empty string, and the client rejects empty tokens.
This example belongs in a server-only module unless the config values are explicitly passed into browser code by a server boundary.
Every request context takes the storefront's i18n definition. Declare it once at module scope with defineShopifyI18n and import it wherever a request context is created:
// lib/i18n.ts
import { defineShopifyI18n } from "@shopify/hydrogen";
// Single-locale storefront. Add `routing` to serve more locales by path prefix or hostname;
// see the hydrogen-markets skill.
export const i18n = defineShopifyI18n({
defaultLocale: { language: "EN", country: "US" },
});
import { createStorefrontClient, createShopifyRequestContext } from "@shopify/hydrogen";
import { i18n } from "./lib/i18n";
const requestContext = createShopifyRequestContext({
request: { headers: new Headers() },
i18n,
locale: i18n.defaultLocale,
});
const client = createStorefrontClient({
type: "public",
requestContext,
config: {
storeDomain: process.env.PUBLIC_STORE_DOMAIN!,
publicStorefrontToken: process.env.PUBLIC_STOREFRONT_API_TOKEN,
},
});
Use when the app has a private token and trusted buyer context. Requires buyerIp to forward trusted buyer context. Resolve request-derived values before creating the client. With a real Request, the locale is matched from request.url against the definition, so no locale override is needed:
import { createStorefrontClient, createShopifyRequestContext } from "@shopify/hydrogen";
import { i18n } from "./lib/i18n";
function getBuyerIp(headers: Headers) {
const buyerIp = headers.get("oxygen-buyer-ip");
if (!buyerIp) throw new Error("oxygen-buyer-ip is required for private SFAPI clients");
return buyerIp;
}
const buyerIp = getBuyerIp(request.headers);
const requestContext = createShopifyRequestContext({
request,
i18n,
buyerIp,
});
const client = createStorefrontClient({
type: "private",
requestContext,
config: {
storeDomain: process.env.PUBLIC_STORE_DOMAIN!,
privateStorefrontToken: process.env.PRIVATE_STOREFRONT_API_TOKEN!,
},
});
Hydrogen does not infer buyer IP headers. Apps decide how to build buyerIp based on their deployment and trusted request data. Common provider defaults:
oxygen-buyer-ipCF-Connecting-IPx-forwarded-forFly-Client-IP (parse X-Forwarded-For only when another reverse proxy sits in front)Use the same request-scoped Storefront client for Hydrogen route handlers, cart server handlers, and server data loaders when they share the same request data. Route, cart, and redirect handlers all accept any provided Storefront client.
When using handleShopifyRoutes, pass the trusted buyerIp into createShopifyRequestContext. Both the SFAPI proxy and direct client.graphql() calls source buyer identity from that request context.
For queries not on behalf of a specific buyer (pre-rendering, static site generation). No buyer IP is forwarded. There is no request URL to match a locale from, so pin one with locale; it must be a locale the definition contains or the request context throws.
const requestContext = createShopifyRequestContext({
request: { headers: new Headers() },
i18n,
locale: i18n.defaultLocale,
});
const client = createStorefrontClient({
type: "private_no_buyer_context",
requestContext,
config: {
storeDomain: process.env.PUBLIC_STORE_DOMAIN!,
privateStorefrontToken: process.env.PRIVATE_STOREFRONT_API_TOKEN!,
},
});
gqlgql is a pre-configured tag with baked-in SFAPI introspection. No codegen, no graphql-config — types are inferred at the type level from the query string.
Customer Account API documents use gql from @shopify/hydrogen/customer-account instead. Keep the two helpers separate so Storefront API documents and Customer Account API documents cannot be mixed.
const SHOP_QUERY = gql(`query { shop { name description } }`);
Fragments compose via a second argument:
const PRODUCT_FIELDS = gql(`fragment ProductFields on Product { title handle }`);
const QUERY = gql(`query { products(first: 10) { nodes { ...ProductFields } } }`, [PRODUCT_FIELDS]);
When customizing predictive search, prefer Hydrogen's additive fragments instead of replacing the full query. This keeps base fields such as trackingParameters, handles, titles, images, and prices available to helpers and result links:
import { gql, makePredictiveSearchQueries } from "@shopify/hydrogen";
const queries = makePredictiveSearchQueries({
fragments: {
product: gql(`
fragment PredictiveSearchProductFragment on Product {
vendor
}
`),
},
});
Use the fragments with createPredictiveSearchServerHandlers({ fragments }), or use the generated query with queryPredictiveSearch(). Read the predictive search skill when wiring autocomplete UI or result URLs.
When adding Storefront API gql() documents to a TypeScript app, add Hydrogen's packed TypeScript plugin to the app's tsconfig.json:
// tsconfig.json
{
"compilerOptions": {
"plugins": [
{
"name": "@shopify/hydrogen/ts-plugin"
}
]
}
}
If the app already has TypeScript plugins, append this plugin without removing framework plugins such as Next.js name: "next". If the app's tsconfig.json extends a generated framework config, add compilerOptions.plugins in the extending tsconfig.json.
The plugin uses the Storefront and Customer Account API schemas shipped by @shopify/hydrogen and writes their generated environments at the project root.
Keep gql(\...`)calls in server/route modules, not client/browser files or barrel files (e.g. anindex.tsthat re-exports everything). Bundlers can't tell whether agql()call has side effects, so anygql()` reachable from browser code gets bundled into the browser.
If the app also authors Customer Account API documents, use @shopify/hydrogen/customer-account; the same plugin validates both APIs.
This plugin provides inline GraphQL autocompletion, validation, and hover docs inside gql() calls. The editor must be configured to use the workspace TypeScript version (not the bundled one) — the bundled TS server does not load plugins.
Read references/query-validation.md when adding or changing gql() documents. The editor plugin does not run during tsc; add hydrogen gql check to a package script and run that script so invalid Storefront API fields fail in CI instead of surfacing as runtime GraphQL errors.
gql() returns a branded query string, not a gql.tada document. Derive result and variable types from the StorefrontApi namespace exported by @shopify/hydrogen:
import { gql, type StorefrontApi } from "@shopify/hydrogen";
const SHOP_QUERY = gql(`query { shop { name } }`);
type ShopResult = StorefrontApi.ResultOf<typeof SHOP_QUERY>;
type ShopVars = StorefrontApi.VariablesOf<typeof SHOP_QUERY>;
Because gql() is a branded string and not a gql.tada document, gql.tada's FragmentOf does not apply (it will not compile). To get a standalone fragment's result type, compose it into a throwaway shape query and read ResultOf off that:
const PRODUCT_CARD = gql(`fragment ProductCard on Product { handle title }`);
const PRODUCT_CARD_SHAPE = gql(
`query { products(first: 1) { nodes { ...ProductCard } } }`,
[PRODUCT_CARD],
);
export type ProductCardData =
StorefrontApi.ResultOf<typeof PRODUCT_CARD_SHAPE>["products"]["nodes"][number];
$country and $language are auto-injected from requestContext.locale when the query declares them as $country: CountryCode and $language: LanguageCode (nullable or !). requestContext.locale is the { language, country, pathPrefix } resolved for this request, also exposed as client.locale. requestContext.i18n and client.i18n are deprecated aliases of it; don't use them. Static clients still create a request context, usually with empty headers plus an explicit locale. You only pass the variables you own:
const PRODUCTS = gql(`
query Products($handle: String!, $country: CountryCode, $language: LanguageCode)
@inContext(country: $country, language: $language) {
collection(handle: $handle) { products(first: 10) { nodes { title } } }
}
`);
const { data } = await client.graphql(PRODUCTS, {
variables: { handle: "summer-sale" },
});
For those declarations the request context wins: the client overwrites any value you pass. The variables type leaves out country and language, but it only reports an error for them when the query has other variables too. If they're the only variables, the type is {} and a passed country still compiles. To query another market, create the client with a request context for that i18n.
A same-named variable of any other type stays yours and keeps its nullability, for example $country: String! as a metafield key, $country: [CountryCode!]!, or $language: ProductSortKeys. Only the first operation's declarations count.
requestContext is passed at client creation so request-scoped cookies, request-group IDs, response-header capture, personalized-response cache safety, and request aborts are centralized. Use one Shopify request context for Storefront and Customer Account clients in the same request. Per-call signal is optional when you need additional cancellation:
const { data } = await client.graphql(QUERY);
const { data } = await client.graphql(QUERY, { signal });
requestContext.signal, per-call signal, and the client's timeout signal are raced automatically. They are combined with AbortSignal.any, which the Next.js edge sandbox does not have, so an edge route or middleware that calls this client needs an AbortSignal.any polyfill installed before the first request. At the final response boundary, append committed session headers first, then call requestContext.applyResponseHeaders(response.headers, response.status). The status keeps the headers of a rate-limited 429 response; see the checklist in "Return 429 from a rate-limited React Router loader".
Read references/caching.md to cache catalog reads across sub-requests on Oxygen-style runtimes.
Transport errors throw. GraphQL errors are returned.
import { StorefrontApiError, StorefrontTimeoutError } from "@shopify/hydrogen";
try {
const { data, errors, headers } = await client.graphql(QUERY);
if (errors) { /* partial GraphQL errors — query succeeded but some fields failed */ }
} catch (error) {
if (error instanceof StorefrontTimeoutError) { /* timed out */ }
if (error instanceof StorefrontApiError) { /* non-200, network failure, or JSON parse error */ }
}
Every successful result includes headers (the raw Headers object from the response) — useful for forwarding Set-Cookie headers in SSR or reading rate-limit metadata.
A 200 response with GraphQL errors does NOT throw — partial success is valid in GraphQL. Non-200 responses, timeouts, network failures, and JSON parse errors all throw StorefrontApiError (or the StorefrontTimeoutError subclass).
On a non-OK response, StorefrontApiError exposes status, requestId, and retryAfter (the raw, unvalidated retry-after header, when the response has one). Redirects, timeouts, network failures, and parse errors leave retryAfter undefined.
429 from a rate-limited React Router loaderAn uncaught StorefrontApiError in a React Router loader renders as HTTP 500, even when its status is 429. Make all three changes:
withStorefrontRateLimit. Without the wrapper, the response stays 500.applyResponseHeaders(response.headers, response.status). Without the status, the response is 429 but has no Retry-After and no Cache-Control: no-store.applyResponseHeaders on the request context of the Storefront API client that the loaders use, for example storefrontClient.requestContext. A different request context has no record of the rate limit, so the result is the same as without the status.import { withStorefrontRateLimit } from "@shopify/hydrogen";
export const loader = withStorefrontRateLimit(async ({ context }: Route.LoaderArgs) => {
const { data } = await context.get(storefrontClientContext).graphql(QUERY);
return data;
});
// app/root.tsx, at the end of the root middleware:
const response = await next();
requestContext.applyResponseHeaders(response.headers, response.status);
return response;
StorefrontApiError with status === 429. It throws a 429 Response with a fixed body, Cache-Control: no-store, and Retry-After when the upstream value is delay-seconds or an IMF-fixdate. Other errors pass through unchanged.error level with scope rate-limit, because React Router doesn't pass thrown responses to handleError. Use configureLogging({ logger }) to send the entry to error reporting. Don't log the error again in the loader.applyResponseHeaders restores Cache-Control: no-store and Retry-After for a 429 after a Storefront API rate limit on the same request context, for page and single-fetch .data responses, so routes don't need a headers export. The method's documentation describes the Retry-After rule. Responses with other statuses keep their cache headers.429 body from error.message, and don't copy upstream headers. The message holds part of the upstream response body.<Await errorElement>.rateLimitHandling: "response" on createCartServerHandlers for cart mutations, on createPredictiveSearchServerHandlers for search, and on handleShopifyRoutes for thrown registered-handler errors, including cart reads. Without the option, each API keeps its previous rate-limit handling. Enabled handlers return 429, Cache-Control: no-store, and a valid Retry-After. With the cart option (mutations only), cart mutations keep code cart_mutation_failed and a native cart form gets the message as plain text; with only the router option, a thrown mutation becomes a JSON rate_limited error, also for a form. Search keeps invalid_predictive_search_request; mapped thrown errors use the generic code rate_limited. Each mapped error is logged once at error level. A direct cartHandlers.get() call still throws, so wrap its loader.Inject a mock fetch at construction — the client calls it instead of the global:
const mockFetch = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ data: { shop: { name: "Test" } } })),
);
const client = createStorefrontClient({
type: "public",
requestContext: createShopifyRequestContext({
request: { headers: new Headers() },
i18n: defineShopifyI18n({ defaultLocale: { language: "EN", country: "US" } }),
}),
config: {
storeDomain: "test.myshopify.com",
publicStorefrontToken: "test-token",
fetch: mockFetch,
},
});
typeof document !== "undefined" guard fires at construction.process.env belong in server-only modules. Browser bundles may leave process.env undefined, inline stale build-time values, or accidentally expose config. Pass safe public values through server data when browser code needs them.private_no_buyer_context clients can be module-scoped when their requestContext uses static headers and an explicit locale. Private per-buyer clients and clients with a real incoming request context must be created per request.define* vs create* — defineShopifyI18n and defineShopifyRouteTemplates return module-scope, serializable configuration that server and client code can both import. createShopifyRequestContext and createStorefrontClient return stateful objects tied to a request or a token; keep them out of shared config modules.Before wiring a client into an app, check whether this skill has a reference file for the app's framework in references/. If one exists, read it and preserve that framework's request context, server data, and buyer-IP conventions. If there is no matching reference, use the core rules above: create request-scoped private clients only inside the server request lifecycle when buyer context exists, keep static public or no-buyer-context clients module-scoped only when they do not depend on request state, and forward captured response headers where the framework allows it.
LICENSE (opens in a new tab)SOURCE.md (opens in a new tab)references/astro.md (opens in a new tab)references/caching.md (opens in a new tab)references/nextjs.md (opens in a new tab)references/nuxt.md (opens in a new tab)references/query-validation.md (opens in a new tab)references/react-router.md (opens in a new tab)references/solidstart.md (opens in a new tab)references/sveltekit.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
11 skills in this plugin
/hydrogen-cart-drawerGuide for building an accessible cart drawer using @shopify/hydrogen. Use when creating or reviewing a cart drawer, mini cart, or slide-out cart, including native dialog element (showModal), closedby light dismiss, body scroll lock, exit animations, and wiring window.Shopify.actions.openCart()./hydrogen-cart-uiBehavioral guide for building cart UI with @shopify/hydrogen: line items, quantity and remove controls, optimistic updates, discount, note, and cart attribute inputs, and the full-page /cart fallback. Use when writing, modifying, or reviewing cart line-item UI, quantity/remove controls, cart mutation forms, or code that changes the cart without a form. Framework agnostic./hydrogen-customer-accountCustomer Account API setup for Hydrogen storefronts. Use when wiring customer sessions, login/logout/OAuth route handlers, account profile, order history, account-gated UI, cart buyer identity sync, or Customer Account GraphQL queries./hydrogen-marketsGuide for implementing Shopify Markets with Hydrogen. Use when adding market routing, country/language localization, Shopify Markets, subdomains, per-market domains, path-prefixed markets, defineShopifyI18n, LocaleProvider, locale switchers, hreflang links, the <html lang> attribute, Next.js App Router market routing, or Storefront API @inContext wiring./hydrogen-oxygenAudit and adapt an existing Hydrogen storefront for Shopify Oxygen and local MiniOxygen. Use when asked to make a server-capable Hydrogen project Oxygen-compatible, add or repair its Worker server entrypoint, configure MiniOxygen, remove Node runtime assumptions, wire Worker environment, cache, and waitUntil, or verify dev, preview, and deploy behavior./hydrogen-predictive-searchGuide for building predictive search with @shopify/hydrogen. Use when adding, modifying, or reviewing autocomplete/search-as-you-type UI, predictive search route handlers, tracking URLs, custom predictive search fragments, or framework predictive search bindings.npx claudepluginhub fcakiroglu16/marketplace --plugin shopify-hydrogen