Template
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:
co-authored by
Claude Opus 5
parent
95b191eeb8
commit
f8c3ef9e0e
+29
-17
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
// Shopify Storefront API Service
|
||||
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`;
|
||||
|
||||
// Shopify API request with optional access token
|
||||
async function shopifyFetch({ query, variables = {} }) {
|
||||
try {
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
// Add access token if available
|
||||
if (SHOPIFY_STOREFRONT_ACCESS_TOKEN) {
|
||||
headers['X-Shopify-Storefront-Access-Token'] = SHOPIFY_STOREFRONT_ACCESS_TOKEN;
|
||||
}
|
||||
|
||||
const response = await fetch(SHOPIFY_STOREFRONT_API_URL, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
query,
|
||||
variables,
|
||||
}),
|
||||
cache: 'no-store', // Ensure fresh data for cart operations
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorBody = await response.text();
|
||||
throw new Error(`Shopify API HTTP error! Status: ${response.status}, Body: ${errorBody}`);
|
||||
}
|
||||
|
||||
const json = await response.json();
|
||||
|
||||
if (json.errors) {
|
||||
console.error('Shopify API errors:', json.errors);
|
||||
throw new Error(`Shopify GraphQL errors: ${JSON.stringify(json.errors)}`);
|
||||
}
|
||||
|
||||
return json;
|
||||
} catch (error) {
|
||||
console.error('Shopify fetch error:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export { shopifyFetch, SHOPIFY_STORE_DOMAIN, SHOPIFY_STOREFRONT_API_URL };
|
||||
@@ -0,0 +1,108 @@
|
||||
// Shopify Storefront API access, backed by `@shopify/hydrogen` (preview build).
|
||||
//
|
||||
// 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.
|
||||
import {
|
||||
createShopifyRequestContext,
|
||||
createStorefrontClient,
|
||||
StorefrontApiError,
|
||||
type AnyStorefrontQueryString,
|
||||
type StorefrontApi,
|
||||
} 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`;
|
||||
|
||||
// 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
|
||||
// over per-request state. `$country`/`$language` are injected from this i18n.
|
||||
const requestContext = createShopifyRequestContext({
|
||||
request: { headers: new Headers() },
|
||||
i18n: { country: 'US', language: 'EN' },
|
||||
});
|
||||
|
||||
// Hydrogen calls `fetch(url, init, cacheOptions)`; Next's caching hints ride
|
||||
// along on `init`, which is how the two ways of caching get to coexist.
|
||||
const fetchWith = (overrides: RequestInit): typeof globalThis.fetch =>
|
||||
((url, init) =>
|
||||
globalThis.fetch(url, { ...init, ...overrides })) as 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,
|
||||
};
|
||||
|
||||
/**
|
||||
* Default client. Uncached, because carts and customer reads must never serve a
|
||||
* stale response.
|
||||
*/
|
||||
export const storefront = createStorefrontClient({
|
||||
type: 'public',
|
||||
requestContext,
|
||||
config: { ...config, fetch: fetchWith({ cache: 'no-store' }) },
|
||||
});
|
||||
|
||||
/**
|
||||
* Client for catalogue 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',
|
||||
requestContext,
|
||||
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.
|
||||
*
|
||||
* 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`.
|
||||
*/
|
||||
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 { SHOPIFY_STORE_DOMAIN, SHOPIFY_STOREFRONT_API_URL };
|
||||
@@ -18,7 +18,8 @@ import {
|
||||
export const CUSTOMER_TOKEN_COOKIE = 'customerAccessToken';
|
||||
|
||||
export interface CustomerUserError {
|
||||
code?: string;
|
||||
/** One of `CustomerErrorCode`; kept as a string so new codes don't break. */
|
||||
code?: string | null;
|
||||
field?: string[] | null;
|
||||
message: string;
|
||||
}
|
||||
@@ -57,7 +58,7 @@ export interface CustomerOrder {
|
||||
|
||||
export interface Customer {
|
||||
id: string;
|
||||
email: string;
|
||||
email: string | null;
|
||||
firstName?: string | null;
|
||||
lastName?: string | null;
|
||||
phone?: string | null;
|
||||
@@ -84,6 +85,13 @@ const firstMessage = (errors: CustomerUserError[]) =>
|
||||
|
||||
export { firstMessage as customerErrorMessage };
|
||||
|
||||
// Shopify returns a null mutation payload when the mutation could not run at
|
||||
// all. That is not a success, so it surfaces as a generic error rather than an
|
||||
// empty error list, which callers read as "it worked".
|
||||
const MUTATION_FAILED: CustomerUserError[] = [
|
||||
{ message: 'Something went wrong. Please try again.' },
|
||||
];
|
||||
|
||||
export async function createCustomer(input: {
|
||||
email: string;
|
||||
password: string;
|
||||
@@ -96,7 +104,10 @@ export async function createCustomer(input: {
|
||||
variables: { input },
|
||||
});
|
||||
|
||||
return { errors: response.data.customerCreate.customerUserErrors ?? [] };
|
||||
const result = response.data.customerCreate;
|
||||
if (!result) return { errors: MUTATION_FAILED };
|
||||
|
||||
return { errors: result.customerUserErrors ?? [] };
|
||||
}
|
||||
|
||||
export async function login(
|
||||
@@ -109,6 +120,7 @@ export async function login(
|
||||
});
|
||||
|
||||
const result = response.data.customerAccessTokenCreate;
|
||||
if (!result) return { token: null, errors: MUTATION_FAILED };
|
||||
|
||||
return {
|
||||
token: result.customerAccessToken ?? null,
|
||||
@@ -152,6 +164,7 @@ export async function resetPassword(
|
||||
});
|
||||
|
||||
const result = response.data.customerReset;
|
||||
if (!result) return { token: null, errors: MUTATION_FAILED };
|
||||
|
||||
return {
|
||||
token: result.customerAccessToken ?? null,
|
||||
@@ -170,6 +183,7 @@ export async function activateAccount(
|
||||
});
|
||||
|
||||
const result = response.data.customerActivate;
|
||||
if (!result) return { token: null, errors: MUTATION_FAILED };
|
||||
|
||||
return {
|
||||
token: result.customerAccessToken ?? null,
|
||||
@@ -210,6 +224,7 @@ export async function updateCustomer(
|
||||
});
|
||||
|
||||
const result = response.data.customerUpdate;
|
||||
if (!result) return { customer: null, errors: MUTATION_FAILED };
|
||||
|
||||
return {
|
||||
customer: result.customer ?? null,
|
||||
|
||||
Reference in New Issue
Block a user