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