Call hydrogen's storefront.graphql directly, drop the compat shim

Completes the migration started in f8c3ef9. That commit put hydrogen
underneath the existing shopifyFetch wrapper; this one removes the
wrapper so every query uses the package's own client API.

- All 22 call sites now call storefront.graphql(DOCUMENT, { variables })
  (cachedStorefront for shop policies) instead of shopifyFetch, which
  emulated the old client's {query, variables} -> {data} shape.
- shopifyFetch is replaced by unwrapStorefrontResult(result, operation),
  which is only an error policy, not a transport wrapper: it returns
  data and throws when Shopify reports GraphQL errors, since hydrogen
  returns those rather than throwing. Naming the operation means a
  failure points at the call site instead of just at "Shopify".
- Environment reads move to services/shopify/config, so client.ts is
  only the hydrogen clients and shop-pay-button no longer imports from
  a query module just to get the store domain.
- Removes @shopify/storefront-api-client, the superseded client. It had
  no importers.

The SHOPIFY_STOREFRONT_API_URL export is gone too — hydrogen builds the
endpoint from storeDomain and apiVersion, and nothing else used it.

No behaviour change intended: same documents, same env var names, same
2025-07 API pin, same caching split between the two clients.

yarn typecheck passes with 0 errors. Verified against mock.shop: build
prerenders the policy pages, and in the browser product grid, search,
collection filters, cart restore, quantity update and discount-code
apply all work with no console errors. Customer account flows remain
untested — they need real credentials.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JaxgqPbFxLsSuLPZom2kdC
This commit is contained in:
Rami Bitar
2026-08-08 10:38:12 -04:00
co-authored by Claude Opus 5
parent f8c3ef9e0e
commit fe78293312
9 changed files with 204 additions and 202 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
'use client';
import React from 'react';
import { SHOPIFY_STORE_DOMAIN } from '@/services/shopify/client';
import { SHOPIFY_STORE_DOMAIN } from '@/services/shopify/config';
import ShopPayLogo from '@/components/shopify/shop-pay-logo';
import { Loader } from '@/components/ui/loader';
import { Button } from '@/components/ui/button';
+36 -26
View File
@@ -1,7 +1,7 @@
'use client';
import { create } from 'zustand';
import { shopifyFetch } from '@/services/shopify/client';
import { storefront, unwrapStorefrontResult } from '@/services/shopify/client';
import {
CREATE_CART_MUTATION,
ADD_CART_LINES_MUTATION,
@@ -119,69 +119,79 @@ function unwrapCartPayload<T>(
}
async function createCartApi(lines: CartLineInput[] = []): Promise<Cart> {
const response = await shopifyFetch({
query: CREATE_CART_MUTATION,
const data = unwrapStorefrontResult(
await storefront.graphql(CREATE_CART_MUTATION, {
variables: { lines: lines.length > 0 ? lines : null },
});
}),
'CreateCart'
);
return unwrapCartPayload(response.data.cartCreate);
return unwrapCartPayload(data.cartCreate);
}
async function addCartLinesApi(
cartId: string,
lines: CartLineInput[]
): Promise<Cart> {
const response = await shopifyFetch({
query: ADD_CART_LINES_MUTATION,
const data = unwrapStorefrontResult(
await storefront.graphql(ADD_CART_LINES_MUTATION, {
variables: { cartId, lines },
});
}),
'AddCartLines'
);
return unwrapCartPayload(response.data.cartLinesAdd);
return unwrapCartPayload(data.cartLinesAdd);
}
async function updateCartLinesApi(
cartId: string,
lines: CartLineUpdateInput[]
): Promise<Cart> {
const response = await shopifyFetch({
query: UPDATE_CART_LINES_MUTATION,
const data = unwrapStorefrontResult(
await storefront.graphql(UPDATE_CART_LINES_MUTATION, {
variables: { cartId, lines },
});
}),
'UpdateCartLines'
);
return unwrapCartPayload(response.data.cartLinesUpdate);
return unwrapCartPayload(data.cartLinesUpdate);
}
async function removeCartLinesApi(
cartId: string,
lineIds: string[]
): Promise<Cart> {
const response = await shopifyFetch({
query: REMOVE_CART_LINES_MUTATION,
const data = unwrapStorefrontResult(
await storefront.graphql(REMOVE_CART_LINES_MUTATION, {
variables: { cartId, lineIds },
});
}),
'RemoveCartLines'
);
return unwrapCartPayload(response.data.cartLinesRemove);
return unwrapCartPayload(data.cartLinesRemove);
}
async function updateCartDiscountCodesApi(
cartId: string,
discountCodes: string[]
): Promise<Cart> {
const response = await shopifyFetch({
query: UPDATE_CART_DISCOUNT_CODES_MUTATION,
const data = unwrapStorefrontResult(
await storefront.graphql(UPDATE_CART_DISCOUNT_CODES_MUTATION, {
variables: { cartId, discountCodes },
});
}),
'UpdateCartDiscountCodes'
);
return unwrapCartPayload(response.data.cartDiscountCodesUpdate);
return unwrapCartPayload(data.cartDiscountCodesUpdate);
}
async function getCartApi(cartId: string): Promise<Cart | null> {
const response = await shopifyFetch({
query: GET_CART_QUERY,
variables: { cartId },
});
const data = unwrapStorefrontResult(
await storefront.graphql(GET_CART_QUERY, { variables: { cartId } }),
'GetCart'
);
return response.data.cart;
return data.cart;
}
export function redirectToCheckout(checkoutUrl: string): void {
+9 -6
View File
@@ -1,4 +1,7 @@
import { shopifyFetch } from '@/services/shopify/client';
import {
cachedStorefront,
unwrapStorefrontResult,
} from '@/services/shopify/client';
import { GET_SHOP_POLICIES_QUERY } from '@/graphql/policies';
export interface ShopPolicy {
@@ -22,12 +25,12 @@ export const POLICY_HANDLES = [
// hourly) rather than the no-store one used for carts and products.
export async function getShopPolicies(): Promise<ShopPolicy[]> {
try {
const { data } = await shopifyFetch({
query: GET_SHOP_POLICIES_QUERY,
cache: true,
});
const data = unwrapStorefrontResult(
await cachedStorefront.graphql(GET_SHOP_POLICIES_QUERY),
'GetShopPolicies'
);
return Object.values(data?.shop ?? {}).filter(
return Object.values(data.shop ?? {}).filter(
(policy): policy is ShopPolicy => Boolean(policy?.handle)
);
} catch (err) {
-1
View File
@@ -17,7 +17,6 @@
"@radix-ui/react-use-controllable-state": "^1.2.6",
"@remixicon/react": "^4.9.0",
"@shopify/hydrogen": "0.0.0-preview-116d5d7-20260730141607",
"@shopify/storefront-api-client": "^1.0.0",
"ai": "^7",
"class-variance-authority": "0.7.1",
"clsx": "^2.1.1",
+41 -31
View File
@@ -4,7 +4,7 @@
// from Route Handlers (see app/api/chat/route.ts) as well as from the client
// hooks in hooks/use-shopify-*.ts, which re-export them.
import type { StorefrontApi } from '@shopify/hydrogen';
import { shopifyFetch } from '@/services/shopify/client';
import { storefront, unwrapStorefrontResult } from '@/services/shopify/client';
import {
GET_PRODUCTS_QUERY,
GET_PRODUCT_QUERY,
@@ -149,12 +149,14 @@ export async function getProductsPage({
sortKey = 'BEST_SELLING',
reverse = false,
}: UseProductsOptions = {}): Promise<ProductsPage> {
const response = await shopifyFetch({
query: GET_PRODUCTS_QUERY,
const data = unwrapStorefrontResult(
await storefront.graphql(GET_PRODUCTS_QUERY, {
variables: { first, after, query, sortKey, reverse },
});
}),
'GetProducts'
);
const { edges, pageInfo } = response.data.products;
const { edges, pageInfo } = data.products;
return {
products: edges.map((edge: { node: Product }) => edge.node),
@@ -165,22 +167,24 @@ export async function getProductsPage({
// Fetch a single product by handle
export async function getProduct(handle: string): Promise<Product | null> {
const response = await shopifyFetch({
query: GET_PRODUCT_QUERY,
variables: { handle },
});
const data = unwrapStorefrontResult(
await storefront.graphql(GET_PRODUCT_QUERY, { variables: { handle } }),
'GetProduct'
);
return response.data.product;
return data.product;
}
// Fetch product recommendations
export async function getProductRecommendations(productId: string): Promise<Product[]> {
const response = await shopifyFetch({
query: QUERY_PRODUCT_RECOMMENDATIONS,
const data = unwrapStorefrontResult(
await storefront.graphql(QUERY_PRODUCT_RECOMMENDATIONS, {
variables: { productId },
});
}),
'GetProductRecommendations'
);
return response.data.productRecommendations || [];
return data.productRecommendations ?? [];
}
@@ -240,12 +244,12 @@ export interface ProductFilterFacet {
// Fetch all collections
export async function getCollections(first = 50): Promise<Collection[]> {
const response = await shopifyFetch({
query: GET_COLLECTIONS_QUERY,
variables: { first },
});
const data = unwrapStorefrontResult(
await storefront.graphql(GET_COLLECTIONS_QUERY, { variables: { first } }),
'GetCollections'
);
return response.data.collections.edges.map((edge: { node: Collection }) => edge.node);
return data.collections.edges.map((edge) => edge.node);
}
// Fetch products in a collection by handle
@@ -272,8 +276,8 @@ export async function getCollectionProductsPage(
): Promise<CollectionProductsPage> {
const filters = parseFilterInputs(filterInputs);
const response = await shopifyFetch({
query: GET_COLLECTION_PRODUCTS_QUERY,
const data = unwrapStorefrontResult(
await storefront.graphql(GET_COLLECTION_PRODUCTS_QUERY, {
variables: {
handle,
first,
@@ -282,9 +286,11 @@ export async function getCollectionProductsPage(
reverse,
filters: filters.length ? filters : null,
},
});
}),
'GetCollectionProducts'
);
const collection = response.data.collection;
const collection = data.collection;
if (!collection) {
return {
collection: null,
@@ -385,8 +391,8 @@ export async function searchProducts({
reverse = false,
filterInputs = [],
}: SearchProductsOptions): Promise<SearchProductsResult> {
const response = await shopifyFetch({
query: SEARCH_PRODUCTS_QUERY,
const data = unwrapStorefrontResult(
await storefront.graphql(SEARCH_PRODUCTS_QUERY, {
variables: {
query,
first,
@@ -397,9 +403,11 @@ export async function searchProducts({
? parseFilterInputs(filterInputs)
: null,
},
});
}),
'SearchProducts'
);
const search = response.data.search;
const search = data.search;
return {
products: search.edges
@@ -418,12 +426,14 @@ export async function searchSuggestions(
query: string,
first = 3
): Promise<{ products: SearchSuggestion[]; totalCount: number }> {
const response = await shopifyFetch({
query: SEARCH_SUGGESTIONS_QUERY,
const data = unwrapStorefrontResult(
await storefront.graphql(SEARCH_SUGGESTIONS_QUERY, {
variables: { query, first },
});
}),
'SearchSuggestions'
);
const search = response.data.search;
const search = data.search;
return {
products: search.edges
+32 -57
View File
@@ -1,23 +1,20 @@
// Shopify Storefront API access, backed by `@shopify/hydrogen` (preview build).
// Storefront API clients, built on `@shopify/hydrogen`.
//
// The package supplies the transport (`createStorefrontClient`) and the typed
// query documents (`gql`, see graphql/*.ts). `shopifyFetch` keeps the call
// shape the rest of the app already uses — `{ query, variables }` in, `{ data }`
// out, throwing on GraphQL errors — but now infers `data` from the document.
// Call sites use the package's own API — `storefront.graphql(DOCUMENT, {
// variables })` — and pass the result through `unwrapStorefrontResult`, which
// applies this app's error policy: fail loudly. Hydrogen deliberately does not
// do that itself, because a 200 carrying partial data and GraphQL errors is a
// valid response that some callers want to render.
import {
createShopifyRequestContext,
createStorefrontClient,
StorefrontApiError,
type AnyStorefrontQueryString,
type StorefrontApi,
type GraphQLFormattedError,
} from '@shopify/hydrogen';
const SHOPIFY_STORE_DOMAIN = process.env.NEXT_PUBLIC_SHOPIFY_DOMAIN;
const SHOPIFY_STOREFRONT_ACCESS_TOKEN =
process.env.NEXT_PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN;
const SHOPIFY_API_VERSION =
process.env.NEXT_PUBLIC_SHOPIFY_API_VERSION || '2025-07';
const SHOPIFY_STOREFRONT_API_URL = `https://${SHOPIFY_STORE_DOMAIN}/api/${SHOPIFY_API_VERSION}/graphql.json`;
import {
SHOPIFY_API_VERSION,
SHOPIFY_STORE_DOMAIN,
SHOPIFY_STOREFRONT_ACCESS_TOKEN,
} from '@/services/shopify/config';
// No incoming request and no buyer context: these clients are module-scoped and
// serve both server rendering and the browser-side hooks, so they must not close
@@ -36,7 +33,6 @@ const fetchWith = (overrides: RequestInit): typeof globalThis.fetch =>
const config = {
storeDomain: SHOPIFY_STORE_DOMAIN!,
apiVersion: SHOPIFY_API_VERSION,
// `mock.shop` and other tokenless storefronts leave this unset.
publicStorefrontToken: SHOPIFY_STOREFRONT_ACCESS_TOKEN,
};
@@ -51,8 +47,8 @@ export const storefront = createStorefrontClient({
});
/**
* Client for catalogue data that changes rarely (shop policies, and anything
* else safe to serve from Next's data cache for an hour).
* Client for data that changes rarely (shop policies, and anything else safe to
* serve from Next's data cache for an hour).
*/
export const cachedStorefront = createStorefrontClient({
type: 'public',
@@ -60,49 +56,28 @@ export const cachedStorefront = createStorefrontClient({
config: { ...config, fetch: fetchWith({ next: { revalidate: 3600 } }) },
});
interface ShopifyFetchArgs<TDoc extends AnyStorefrontQueryString> {
query: TDoc;
variables?: StorefrontApi.VariablesOf<TDoc>;
/** Serve from Next's data cache instead of hitting Shopify every time. */
cache?: boolean;
}
/**
* Runs a `gql()` document and returns its data.
* Returns the data from a `graphql()` result, throwing if Shopify reported any
* GraphQL errors. Transport failures — non-200, timeouts, unparseable bodies —
* have already thrown as `StorefrontApiError` by this point.
*
* Hydrogen returns GraphQL errors rather than throwing them (a 200 with partial
* data is still a valid response), so this re-raises them to preserve the
* fail-loudly behaviour the callers were written against. Transport failures
* already throw as `StorefrontApiError`.
* `operation` names the query in the log and the thrown message, so a failure
* points at the call site rather than just at "Shopify".
*/
export async function shopifyFetch<TDoc extends AnyStorefrontQueryString>({
query,
variables,
cache = false,
}: ShopifyFetchArgs<TDoc>): Promise<{
data: StorefrontApi.ResultOf<TDoc>;
}> {
const client = cache ? cachedStorefront : storefront;
try {
const { data, errors } = await client.graphql(query, {
variables,
} as never);
if (errors?.length) {
console.error('Shopify API errors:', errors);
throw new Error(`Shopify GraphQL errors: ${JSON.stringify(errors)}`);
export function unwrapStorefrontResult<TData>(
result: { data: TData | null; errors?: GraphQLFormattedError[] },
operation: string
): TData {
if (result.errors?.length) {
console.error(`Shopify GraphQL errors (${operation}):`, result.errors);
throw new Error(
`Shopify GraphQL errors (${operation}): ${JSON.stringify(result.errors)}`
);
}
return { data: data as StorefrontApi.ResultOf<TDoc> };
} catch (error) {
if (error instanceof StorefrontApiError) {
console.error('Shopify fetch error:', error.toJSON());
} else {
console.error('Shopify fetch error:', error);
}
throw error;
if (result.data == null) {
throw new Error(`Shopify returned no data for ${operation}.`);
}
return result.data;
}
export { SHOPIFY_STORE_DOMAIN, SHOPIFY_STOREFRONT_API_URL };
+12
View File
@@ -0,0 +1,12 @@
// Storefront configuration, read from the environment in one place.
//
// These are all `NEXT_PUBLIC_*`, so Next inlines them at build time and they are
// safe to read from client components as well as server code.
export const SHOPIFY_STORE_DOMAIN = process.env.NEXT_PUBLIC_SHOPIFY_DOMAIN;
/** Omitted for tokenless storefronts such as `mock.shop`. */
export const SHOPIFY_STOREFRONT_ACCESS_TOKEN =
process.env.NEXT_PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN;
export const SHOPIFY_API_VERSION =
process.env.NEXT_PUBLIC_SHOPIFY_API_VERSION || '2025-07';
+39 -29
View File
@@ -3,7 +3,7 @@
// The customer access token is a credential: it is only ever handled here and
// in the /api/account route handlers, and is stored in an httpOnly cookie so
// client JavaScript can never read it.
import { shopifyFetch } from '@/services/shopify/client';
import { storefront, unwrapStorefrontResult } from '@/services/shopify/client';
import {
CUSTOMER_QUERY,
CUSTOMER_CREATE_MUTATION,
@@ -99,12 +99,14 @@ export async function createCustomer(input: {
lastName?: string;
acceptsMarketing?: boolean;
}): Promise<{ errors: CustomerUserError[] }> {
const response = await shopifyFetch({
query: CUSTOMER_CREATE_MUTATION,
const data = unwrapStorefrontResult(
await storefront.graphql(CUSTOMER_CREATE_MUTATION, {
variables: { input },
});
}),
'CustomerCreate'
);
const result = response.data.customerCreate;
const result = data.customerCreate;
if (!result) return { errors: MUTATION_FAILED };
return { errors: result.customerUserErrors ?? [] };
@@ -114,12 +116,14 @@ export async function login(
email: string,
password: string
): Promise<AuthResult> {
const response = await shopifyFetch({
query: CUSTOMER_ACCESS_TOKEN_CREATE_MUTATION,
const data = unwrapStorefrontResult(
await storefront.graphql(CUSTOMER_ACCESS_TOKEN_CREATE_MUTATION, {
variables: { input: { email, password } },
});
}),
'CustomerAccessTokenCreate'
);
const result = response.data.customerAccessTokenCreate;
const result = data.customerAccessTokenCreate;
if (!result) return { token: null, errors: MUTATION_FAILED };
return {
@@ -130,8 +134,7 @@ export async function login(
export async function logout(accessToken: string): Promise<void> {
try {
await shopifyFetch({
query: CUSTOMER_ACCESS_TOKEN_DELETE_MUTATION,
await storefront.graphql(CUSTOMER_ACCESS_TOKEN_DELETE_MUTATION, {
variables: { customerAccessToken: accessToken },
});
} catch (err) {
@@ -144,8 +147,7 @@ export async function logout(accessToken: string): Promise<void> {
// would leak account membership.
export async function recoverPassword(email: string): Promise<void> {
try {
await shopifyFetch({
query: CUSTOMER_RECOVER_MUTATION,
await storefront.graphql(CUSTOMER_RECOVER_MUTATION, {
variables: { email },
});
} catch (err) {
@@ -158,12 +160,14 @@ export async function resetPassword(
resetToken: string,
password: string
): Promise<AuthResult> {
const response = await shopifyFetch({
query: CUSTOMER_RESET_MUTATION,
const data = unwrapStorefrontResult(
await storefront.graphql(CUSTOMER_RESET_MUTATION, {
variables: { id, input: { resetToken, password } },
});
}),
'CustomerReset'
);
const result = response.data.customerReset;
const result = data.customerReset;
if (!result) return { token: null, errors: MUTATION_FAILED };
return {
@@ -177,12 +181,14 @@ export async function activateAccount(
activationToken: string,
password: string
): Promise<AuthResult> {
const response = await shopifyFetch({
query: CUSTOMER_ACTIVATE_MUTATION,
const data = unwrapStorefrontResult(
await storefront.graphql(CUSTOMER_ACTIVATE_MUTATION, {
variables: { id, input: { activationToken, password } },
});
}),
'CustomerActivate'
);
const result = response.data.customerActivate;
const result = data.customerActivate;
if (!result) return { token: null, errors: MUTATION_FAILED };
return {
@@ -196,12 +202,14 @@ export async function getCustomer(
orderCount = 10
): Promise<Customer | null> {
try {
const response = await shopifyFetch({
query: CUSTOMER_QUERY,
const data = unwrapStorefrontResult(
await storefront.graphql(CUSTOMER_QUERY, {
variables: { customerAccessToken: accessToken, orderCount },
});
}),
'GetCustomer'
);
return response.data.customer ?? null;
return data.customer ?? null;
} catch (err) {
// An expired or revoked token reads as "not signed in".
console.error('Failed to load customer:', err);
@@ -218,12 +226,14 @@ export async function updateCustomer(
phone?: string;
}
): Promise<{ customer: Customer | null; errors: CustomerUserError[] }> {
const response = await shopifyFetch({
query: CUSTOMER_UPDATE_MUTATION,
const data = unwrapStorefrontResult(
await storefront.graphql(CUSTOMER_UPDATE_MUTATION, {
variables: { customerAccessToken: accessToken, customer },
});
}),
'CustomerUpdate'
);
const result = response.data.customerUpdate;
const result = data.customerUpdate;
if (!result) return { customer: null, errors: MUTATION_FAILED };
return {
-17
View File
@@ -1881,13 +1881,6 @@ __metadata:
languageName: node
linkType: hard
"@shopify/graphql-client@npm:^1.4.2":
version: 1.4.2
resolution: "@shopify/graphql-client@npm:1.4.2"
checksum: 10c0/f18d898ec3fb12a819b6c2941d9ddaebd1ab7152ffe55450ab9255c11860de9422ba1e9eadee5f44ef314f664fe411c642ba3debd6671851b9cdc647eb85e0be
languageName: node
linkType: hard
"@shopify/hydrogen@npm:0.0.0-preview-116d5d7-20260730141607":
version: 0.0.0-preview-116d5d7-20260730141607
resolution: "@shopify/hydrogen@npm:0.0.0-preview-116d5d7-20260730141607"
@@ -1907,15 +1900,6 @@ __metadata:
languageName: node
linkType: hard
"@shopify/storefront-api-client@npm:^1.0.0":
version: 1.0.10
resolution: "@shopify/storefront-api-client@npm:1.0.10"
dependencies:
"@shopify/graphql-client": "npm:^1.4.2"
checksum: 10c0/e8eff260e91857e87cffb543ca57c8a4a6e549316e0b6ccef2c345b857ef59e4092e92ecd2904706aa386bca1d21af4ef3e7447f9966b8dcceda06b3ad7dadc9
languageName: node
linkType: hard
"@standard-schema/spec@npm:^1.1.0":
version: 1.1.0
resolution: "@standard-schema/spec@npm:1.1.0"
@@ -3486,7 +3470,6 @@ __metadata:
"@radix-ui/react-use-controllable-state": "npm:^1.2.6"
"@remixicon/react": "npm:^4.9.0"
"@shopify/hydrogen": "npm:0.0.0-preview-116d5d7-20260730141607"
"@shopify/storefront-api-client": "npm:^1.0.0"
"@tailwindcss/postcss": "npm:^4"
"@types/hast": "npm:^3.0.5"
"@types/node": "npm:^22"