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
+14 -29
View File
@@ -1,4 +1,4 @@
import { SHOPIFY_STOREFRONT_API_URL } from '@/services/shopify/client';
import { shopifyFetch } from '@/services/shopify/client';
import { GET_SHOP_POLICIES_QUERY } from '@/graphql/policies';
export interface ShopPolicy {
@@ -9,12 +9,6 @@ export interface ShopPolicy {
url: string;
}
interface ShopPoliciesResponse {
data?: {
shop?: Record<string, ShopPolicy | null>;
};
}
// Handles Shopify uses for each policy — also the routes under /policies/[handle].
export const POLICY_HANDLES = [
'terms-of-service',
@@ -24,32 +18,23 @@ export const POLICY_HANDLES = [
'subscription-policy',
] as const;
// Policies change rarely, so this uses its own fetch (revalidated hourly)
// rather than the no-store `shopifyFetch` used for carts and products.
// Policies change rarely, so this reads through the cached client (revalidated
// hourly) rather than the no-store one used for carts and products.
export async function getShopPolicies(): Promise<ShopPolicy[]> {
const token = process.env.NEXT_PUBLIC_SHOPIFY_STOREFRONT_ACCESS_TOKEN;
try {
const { data } = await shopifyFetch({
query: GET_SHOP_POLICIES_QUERY,
cache: true,
});
const response = await fetch(SHOPIFY_STOREFRONT_API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(token ? { 'X-Shopify-Storefront-Access-Token': token } : {}),
},
body: JSON.stringify({ query: GET_SHOP_POLICIES_QUERY }),
next: { revalidate: 3600 },
});
if (!response.ok) {
console.error('Failed to load shop policies:', response.status);
return Object.values(data?.shop ?? {}).filter(
(policy): policy is ShopPolicy => Boolean(policy?.handle)
);
} catch (err) {
// A storefront without policies configured shouldn't break the footer.
console.error('Failed to load shop policies:', err);
return [];
}
const json: ShopPoliciesResponse = await response.json();
const shop = json.data?.shop ?? {};
return Object.values(shop).filter((policy): policy is ShopPolicy =>
Boolean(policy?.handle)
);
}
export async function getShopPolicy(