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
+62 -52
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,
variables: { first, after, query, sortKey, reverse },
});
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,
variables: { productId },
});
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,19 +276,21 @@ export async function getCollectionProductsPage(
): Promise<CollectionProductsPage> {
const filters = parseFilterInputs(filterInputs);
const response = await shopifyFetch({
query: GET_COLLECTION_PRODUCTS_QUERY,
variables: {
handle,
first,
after,
sortKey,
reverse,
filters: filters.length ? filters : null,
},
});
const data = unwrapStorefrontResult(
await storefront.graphql(GET_COLLECTION_PRODUCTS_QUERY, {
variables: {
handle,
first,
after,
sortKey,
reverse,
filters: filters.length ? filters : null,
},
}),
'GetCollectionProducts'
);
const collection = response.data.collection;
const collection = data.collection;
if (!collection) {
return {
collection: null,
@@ -385,21 +391,23 @@ export async function searchProducts({
reverse = false,
filterInputs = [],
}: SearchProductsOptions): Promise<SearchProductsResult> {
const response = await shopifyFetch({
query: SEARCH_PRODUCTS_QUERY,
variables: {
query,
first,
after,
sortKey,
reverse,
productFilters: filterInputs.length
? parseFilterInputs(filterInputs)
: null,
},
});
const data = unwrapStorefrontResult(
await storefront.graphql(SEARCH_PRODUCTS_QUERY, {
variables: {
query,
first,
after,
sortKey,
reverse,
productFilters: filterInputs.length
? 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,
variables: { query, first },
});
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
+34 -59
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)}`);
}
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;
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)}`
);
}
}
export { SHOPIFY_STORE_DOMAIN, SHOPIFY_STOREFRONT_API_URL };
if (result.data == null) {
throw new Error(`Shopify returned no data for ${operation}.`);
}
return result.data;
}
+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';
+45 -35
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,
variables: { input },
});
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,
variables: { input: { email, password } },
});
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,
variables: { id, input: { resetToken, password } },
});
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,
variables: { id, input: { activationToken, password } },
});
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,
variables: { customerAccessToken: accessToken, orderCount },
});
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,
variables: { customerAccessToken: accessToken, customer },
});
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 {