Move Storefront queries onto @shopify/hydrogen preview client

Replaces the hand-rolled shopifyFetch wrapper and raw query strings with
the hydrogen preview package (0.0.0-preview-116d5d7-20260730141607), the
same build pinned in hydrogen-preview/.

- services/shopify/client: createStorefrontClient({type: "public"}) with a
  static request context. Two module-scoped clients — uncached for carts,
  products and customers; revalidate-3600 for shop policies — using the
  client's custom fetch option to carry Next's caching hints.
- graphql/*: every document wrapped in gql(), fragments composed via the
  second argument instead of string interpolation, and $country/$language
  declared with @inContext so hydrogen injects them.
- shopifyFetch keeps its {query, variables} call shape so call sites are
  unchanged, but is now generic over the document, so data is inferred. It
  re-raises GraphQL errors, which hydrogen returns rather than throws.

Env var names, the 2025-07 API version pin, and the client-side fetching
architecture are unchanged.

Turning on type coverage surfaced real defects, not just annotations:

- hydrogen gql check caught $discountCodes: [String!] used where the field
  requires [String!]!.
- Cart and customer mutation payloads are nullable and were dereferenced
  unconditionally, so a failed mutation threw a TypeError. Adds a shared
  unwrapCartPayload helper (collapsing five copies of the same userErrors
  check) and explicit null handling in the customer service, so a null
  payload reads as an error rather than success with no errors.
- Search results are a Product | Page | Article union; adds __typename to
  the queries and narrows on it.
- Widens nullable fields (altText, image, customer.email, totalTaxAmount)
  in the domain interfaces and in the structural duplicates some
  components declare locally.

Adds a typecheck script (tsc --noEmit && hydrogen gql check); it passes
with 0 errors. Two deprecation warnings are left alone as acting on them
would change behaviour: ProductOption.values and CartCost.totalTaxAmount.

Verified against mock.shop: build prerenders the policy pages through the
cached client, and in the browser the product grid, search with facets,
collection filter round-trip, add-to-cart and quantity update all work.
Customer account flows are 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:24:38 -04:00
co-authored by Claude Opus 5
parent 95b191eeb8
commit f8c3ef9e0e
21 changed files with 468 additions and 215 deletions
+29 -17
View File
@@ -3,6 +3,7 @@
// These are plain async functions with no React imports, so they can be called
// 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 {
GET_PRODUCTS_QUERY,
@@ -18,9 +19,11 @@ import {
SEARCH_SUGGESTIONS_QUERY,
} from '@/graphql/search';
// Optional fields are `| null` rather than just optional: the Storefront API
// returns explicit nulls, and the typed `gql()` documents now surface that.
interface ProductImage {
url: string;
altText?: string;
altText?: string | null;
}
interface ProductPrice {
@@ -37,7 +40,7 @@ interface ProductVariant {
name: string;
value: string;
}>;
image?: ProductImage;
image?: ProductImage | null;
}
export interface ProductOptionValue {
@@ -183,7 +186,7 @@ export async function getProductRecommendations(productId: string): Promise<Prod
interface CollectionImage {
url: string;
altText?: string;
altText?: string | null;
}
export interface Collection {
@@ -192,7 +195,7 @@ export interface Collection {
handle: string;
description?: string;
descriptionHtml?: string;
image?: CollectionImage;
image?: CollectionImage | null;
}
export interface CollectionWithProducts extends Collection {
@@ -267,14 +270,7 @@ export async function getCollectionProductsPage(
filterInputs = [],
}: UseCollectionProductsOptions = {}
): Promise<CollectionProductsPage> {
const filters = filterInputs.flatMap((input) => {
try {
return [JSON.parse(input)];
} catch {
console.warn('Ignoring malformed product filter input:', input);
return [];
}
});
const filters = parseFilterInputs(filterInputs);
const response = await shopifyFetch({
query: GET_COLLECTION_PRODUCTS_QUERY,
@@ -342,7 +338,7 @@ export interface SearchSuggestion {
handle: string;
featuredImage?: {
url: string;
altText?: string;
altText?: string | null;
} | null;
priceRange: {
minVariantPrice: {
@@ -362,10 +358,18 @@ interface SearchProductsOptions {
filterInputs?: string[];
}
function parseFilterInputs(inputs: string[]): unknown[] {
// The `ProductFilter` input shape, taken from the query that consumes it so it
// tracks the schema rather than being restated here.
type ProductFilterInput = NonNullable<
StorefrontApi.VariablesOf<typeof GET_COLLECTION_PRODUCTS_QUERY>['filters']
>[number];
// Facet `input` values are opaque JSON strings produced by Shopify and handed
// straight back as filter inputs, so they are parsed, not constructed.
function parseFilterInputs(inputs: string[]): ProductFilterInput[] {
return inputs.flatMap((input) => {
try {
return [JSON.parse(input)];
return [JSON.parse(input) as ProductFilterInput];
} catch {
console.warn('Ignoring malformed product filter input:', input);
return [];
@@ -398,7 +402,11 @@ export async function searchProducts({
const search = response.data.search;
return {
products: search.edges.map((edge: { node: Product }) => edge.node),
products: search.edges
.map((edge) => edge.node)
.filter((node): node is Extract<typeof node, { __typename: 'Product' }> =>
node.__typename === 'Product'
),
totalCount: search.totalCount ?? 0,
filters: search.productFilters ?? [],
hasNextPage: Boolean(search.pageInfo?.hasNextPage),
@@ -418,7 +426,11 @@ export async function searchSuggestions(
const search = response.data.search;
return {
products: search.edges.map((edge: { node: SearchSuggestion }) => edge.node),
products: search.edges
.map((edge) => edge.node)
.filter((node): node is Extract<typeof node, { __typename: 'Product' }> =>
node.__typename === 'Product'
),
totalCount: search.totalCount ?? 0,
};
}