Storefront API client
The createStorefrontClient function creates a typed Storefront API client for browser code, server-side rendering, or background jobs such as webhooks. Use the client to run queries and mutations with the customer's cookies and locale, and to cache query results.
Import createStorefrontClient and its option and client types from @shopify/hydrogen.
Pass the client a request context from createShopifyRequestContext.
To choose a client type, localize queries, and handle errors, refer to Query the Storefront API.
Anchor to Client setupClient setup
Creates a Storefront API client that runs typed queries and mutations against your store.
Set type based on where your code runs and whether customer context is available:
public | private | | |
|---|---|---|---|
| Runs in | Browser or mobile | Server-side rendering | Background server code |
| Token | Public access token, or none | Private access token | Private access token |
| Customer context | Browser request context | You forward trusted | None |
| Best for | Client-side fetches | SSR with customer context | Webhooks, background jobs |
Pass a request context from . The client forwards the incoming request's cookies and Sec-GPC header to the Storefront API, and fills $country and $language variables from the context's locale. The client reads the request headers once, when you create the client. Create a client for each incoming request, and create a client at module scope only with a static request context.
Keep private clients in server code, where the token can't reach browsers. The function throws an error when you create either private client type in a browser. The function throws a when the request context of a private client has no .
- Anchor to argsargsargsCreateStorefrontClientArgsCreateStorefrontClientArgsrequiredrequired
The client type, request context, and store configuration for the new client.
The client, with a
graphql()method that runs queries and mutations.
CreateStorefrontClientArgs
StorefrontClient
A Storefront API client. Call `graphql()` with a document to run a query or mutation and get a typed result.
- apiUrl
The Storefront API GraphQL endpoint that the client calls.
string - graphql
Runs a Storefront API query or mutation and returns a typed result. Pass a `gql` document or a plain query string. When the operation declares `$country: CountryCode` or `$language: LanguageCode`, the client sets the variable from the request context and overrides any value you pass. Variables with other types stay caller-owned. The method throws an error when a query passes a `cache` strategy and the client has no cache, or when the strategy uses `private` mode. A catch block for `StorefrontApiError` doesn't catch this configuration error. To cache customer-specific data, use `createRunWithCache` with a key unique to the customer.
<const Doc extends DocLike | string>(doc: Doc, ...options: GqlRestParam<ResolveDoc<Doc>, Extra>) => Promise<StorefrontGraphqlResult<ResolveDoc<Doc>>> - i18n
The locale resolved for this request.
RequestContext["i18n"] - locale
The locale resolved for this request. The client sends its country and language for `$country` and `$language` variables.
RequestContext["locale"] - requestContext
The request context that you passed to `createStorefrontClient`.
RequestContext - storefrontId
The storefront ID from the client options.
string - storeUrl
Your store's URL with its protocol, such as `https://my-store.myshopify.com`.
string - type
The client type that you passed to `createStorefrontClient`.
Type
DocLike
A document that the client's GraphQL method accepts, from `gql` or from `gql`.tada.
TadaDocumentNode<any, any> | AnyStorefrontQueryStringAnyStorefrontQueryString
Any `gql` document, whatever its result and variables types. Use the type to accept any Storefront API document.
string & StorefrontQueryMetadataStorefrontQueryMetadata
Type-only properties that mark a string as a `gql` document.
- __hydrogenQueryBrand
Marks a string that `gql` returns. The property exists only in types.
true - __hydrogenQueryParts
The operation text followed by each distinct fragment text the document appends. The property exists only in types.
Parts - __hydrogenQuerySource
The document's query text, which TypeScript reads to infer types. The property exists only in types.
Source
GqlRestParam
The options argument of a GraphQL call. Pass the options argument when the document declares a required variable. You can leave the options argument out when every variable is optional, or when the only required variables are `$country` and `$language`, which the client fills.
HasNoRequiredKeys<MergedOptions<Doc, GraphqlExtraOptionsForDoc<Doc, Extra>>> extends true
? [options?: MergedOptions<Doc, GraphqlExtraOptionsForDoc<Doc, Extra>>]
: [options: MergedOptions<Doc, GraphqlExtraOptionsForDoc<Doc, Extra>>]HasNoRequiredKeys
Resolves to `true` when an object type has no required keys.
Record<string, never> extends T ? true : falseMergedOptions
The options for a GraphQL call. The call needs `variables` only when the document declares a required variable.
Extra & StorefrontGraphqlOptions & (HasNoRequiredKeys<UserVariables<Doc>> extends true
? { variables?: UserVariables<Doc> }
: { variables: UserVariables<Doc> })StorefrontGraphqlOptions
Options that every Storefront API GraphQL call accepts.
- signal
Cancels the request when the signal aborts. The request context's signal and the client timeout also cancel the request. The signal doesn't cancel a stale-while-revalidate refresh.
AbortSignal
UserVariables
Variables the caller passes: everything except the i18n variables the client injects.
VariablesOfDoc
The variables that a Customer Account document declares.
Doc extends CustomerAccountDocument<unknown, infer Variables, string> ? Variables : neverCustomerAccountDocument
A Customer Account API query or mutation that `gql` from `@shopify/hydrogen/customer-account` returns. TypeScript infers the result and variables types from the document's GraphQL source. Create documents only with the Customer Account `gql` function. The client throws a `TypeError` for any other object.
DocumentDecoration<Result, Variables> & {
readonly [CUSTOMER_ACCOUNT_DOCUMENT]: true;
readonly source: Source;
/** The operation text followed by each distinct fragment text the document appends. The property exists only in types. */
readonly parts?: Parts;
}I18nVariableNamesOfDoc
The variables the client fills when omitted: those declared with the expected type, such as `$language: LanguageCode`.
string extends SourceOf<Doc>
? I18nVariableNamesByValue<VariablesOfDoc<Doc>>
: InferVariableNamesDeclaredAs<SourceOf<Doc>, I18nVariableTypes>SourceOf
Extracts the source string literal type from a Customer Account document.
Doc extends { readonly source: infer Source extends string }
? Source
: neverI18nVariableNamesByValue
I18nVariableNamesByValue<Variables>InferVariableNamesDeclaredAs
Names of the first operation's variables that are declared with the named type `Types` maps them to, nullable or non-null. List types never match.
parseDocument<T> extends infer Doc
? Doc extends { kind: "Document"; definitions: infer Defs extends readonly unknown[] }
? FirstOperation<Defs> extends { variableDefinitions: infer Vars extends readonly unknown[] }
? DeclaredNameOfType<Vars[number], Types>
: never
: never
: neverFirstOperation
Defs extends readonly [infer Def, ...infer Rest]
? Def extends { kind: "OperationDefinition" }
? Def
: FirstOperation<Rest>
: neverDeclaredNameOfType
Definition extends {
variable: { name: { value: infer Name extends keyof Types } };
type: infer Type;
}
? (Type extends { kind: "NonNullType"; type: infer Inner } ? Inner : Type) extends {
kind: "NamedType";
name: { value: Types[Name] };
}
? Name
: never
: neverDefinition
A top-level definition of a GraphQL text. A fragment is keyed by its name, any other definition by its canonical form. `canonical` joins the definition's tokens with single spaces, so two copies that differ only in whitespace, commas, or comments compare equal. `text` is the definition as written.
- canonical
string - key
string - text
string
I18nVariableTypes
typeof CUSTOMER_ACCOUNT_I18N_VARIABLE_TYPESGraphqlExtraOptionsForDoc
Offers the `cache` option only for documents that TypeScript recognizes as queries.
OperationKindOfDoc<Doc> extends "query" ? Extra : Omit<Extra, "cache">OperationKindOfDoc
The operation kind of a document, such as `query`. Resolves to `unknown` when the query text isn't a string literal type.
[SourceText<Doc>] extends [never]
? "unknown"
: string extends SourceText<Doc>
? "unknown"
: InferOperationKind<SourceText<Doc>>SourceText
The query text of a document as a string literal type. A plain string resolves to itself.
[SourceOf<Doc>] extends [never]
? Doc extends string
? Doc
: never
: SourceOf<Doc>InferOperationKind
The operation kind of a query string, such as `query`. Resolves to `unknown` unless the query text has exactly one operation.
parseDocument<T> extends infer Doc
? [Doc] extends [never]
? "unknown"
: OperationKindType<Doc>
: "unknown"OperationKindType
ResolveDoc
The typed document for a GraphQL call. Hydrogen infers the types when you pass a plain query string.
D extends DocLike ? D : D extends string ? InferredDoc<D> : neverInferredDoc
StorefrontGraphqlResult
The result of a GraphQL call, with the data, any GraphQL errors, and the response headers. Check `errors` before you read `data`. Without errors, `data` holds the full result, typed from your document. With errors, `data` is `null` after a request error or after a failed non-null field at the root. Otherwise, `data` holds a partial result, and `null` replaces each failed field or its nearest nullable parent.
{ data: ResultOfDoc<Doc>; errors?: undefined; headers: Headers } | { data: ResultOfDoc<Doc> | null; errors: GraphQLFormattedError[]; headers: Headers }ResultOfDoc
The result type of a `gql` document or a `gql`.tada document node.
Doc extends StorefrontQueryString<infer Result, infer _Variables, string>
? Result
: Doc extends TadaDocumentNode<any, any>
? TadaResultOf<Doc>
: neverStorefrontQueryString
Headers
GraphQLFormattedError
A GraphQL error from the Storefront API. The result of a GraphQL call lists GraphQL errors in its `errors` field.
- extensions
Extra details that the Storefront API adds to the error.
Record<string, unknown> - locations
The lines and columns in the query where the error occurs.
ReadonlyArray<{ line: number; column: number }> - message
The error message.
string - path
The path to the response field that failed.
ReadonlyArray<string | number>
The config options depend on the client type. A public client takes PublicClientOptions, a private client takes PrivateClientOptions, and a private_no_buyer_context client takes PrivateNoBuyerContextClientOptions.
Anchor to publicclientoptionsPublicClientOptions
Options for a public client, which runs in the browser or a mobile app. Pass a public access token, or omit the token for tokenless access.
Tokenless access can't read some Storefront API fields, including product tags, metaobjects, metafields, menus, and customers.
- Anchor to storeDomainstore
Domainstore Domain stringstringrequiredrequired Your store's domain, such as
my-store.myshopify.com. Hydrogen addshttps://when the domain has no protocol, and removes trailing slashes.throws an error for an empty domain.- Anchor to apiVersionapi
Versionapi Version stringstring The Storefront API version that the client queries. Defaults to the version that Hydrogen bundles. To send some queries to another version, such as
unstable, create a second client with that version. Type inference always uses Hydrogen's bundled schema. Write your own types for fields outside the bundled schema.- Anchor to cachecachecacheCacheInstanceCacheInstance
The cache that stores query results. The client caches only queries that pass a
cachestrategy. The client never caches mutations, results with GraphQL errors, or responses whoseCache-Controlheader containsprivateorno-store. A response with either directive also makes the final response private when you call, whether or not the query passes acachestrategy.- Anchor to defaultTimeoutInMsdefault
Timeout In Msdefault Timeout In Ms numbernumber How long a request can run before the client throws a
, in milliseconds. Defaults to30000. Set0to turn off the timeout. Stale-while-revalidate refreshes use the same timeout, or 30,000 when the timeout is0.throws an error for a negative value.- Anchor to fetchfetchfetchFetchFetch
The fetch function that the client calls. Defaults to
.throws an error when neither exists.- Anchor to publicStorefrontTokenpublic
Storefront Tokenpublic Storefront Token string | undefinedstring | undefined Your public Storefront API access token. Omit the token for tokenless access.
throws an error for an empty string.- Anchor to storefrontIdstorefront
Idstorefront Id stringstring Your Hydrogen storefront's ID. The client sends the ID in the
Shopify-Storefront-Idheader of every request.- Anchor to waitUntilwait
Untilwait Until WaitUntilWaitUntil Keeps the runtime alive while the client writes to the cache in the background, such as a worker's
function. Without the function, each cached query waits for its cache write before it resolves.
CacheInstance
The cache that holds entries, either a Web Cache API cache or a key-value store.
WebCacheLike | KeyValueCacheLikeWebCacheLike
A cache with the `match()`, `put()`, and `delete()` methods of the Web Cache API, such as a cache from `caches.open()`.
- delete
The **`delete()`** method of the Cache interface finds the Cache entry whose key is the request, and if found, deletes the Cache entry and returns a Promise that resolves to `true`. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Cache/delete)
(request: RequestInfo | URL, options?: CacheQueryOptions) => Promise<boolean> - match
The **`match()`** method of the Cache interface returns a Promise that resolves to the Response associated with the first matching request in the Cache object. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Cache/match)
(request: RequestInfo | URL, options?: CacheQueryOptions) => Promise<Response> - put
The **`put()`** method of the Often, you will just want to Window/fetch one or more requests, then add the result straight to your cache. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Cache/put)
(request: RequestInfo | URL, response: Response) => Promise<void>
KeyValueCacheLike
A key-value store with `get()`, `set()`, and an optional `delete()` method. Hydrogen passes each entry to `set()` as an object. Serialize the object in your store when the store saves only strings.
- delete
Removes the value under the key.
(key: string) => unknown - get
Returns the value under the key. Hydrogen treats a value that it didn't write as a cache miss.
(key: string) => unknown - set
Saves the value under the key. Expire the entry after the `ttl` option, in seconds.
(key: string, value: unknown, options?: KeyValueCacheSetOptions) => unknown
KeyValueCacheSetOptions
Options that Hydrogen passes when it writes an entry to a key-value store.
- ttl
How many seconds to keep the entry. Hydrogen passes the sum of the strategy's `maxAge`, `staleWhileRevalidate`, and `staleIfError`, rounded up.
number
WaitUntil
Keeps the runtime alive until a background cache write or refresh finishes, such as a worker's `waitUntil` function. Hydrogen ignores errors that the function throws.
- promise
The background cache write or refresh to wait for.
Promise<unknown>
Nothing. Hydrogen ignores the return value.
voidAnchor to privateclientoptionsPrivateClientOptions
Options for a private client, which runs during server-side rendering and forwards the customer's IP address to the Storefront API. Set on the request context before you create the client.
- Anchor to privateStorefrontTokenprivate
Storefront Tokenprivate Storefront Token stringstringrequiredrequired Your private Storefront API access token. Keep the token out of browser code.
throws an error when the token is missing.- Anchor to storeDomainstore
Domainstore Domain stringstringrequiredrequired Your store's domain, such as
my-store.myshopify.com. Hydrogen addshttps://when the domain has no protocol, and removes trailing slashes.throws an error for an empty domain.- Anchor to apiVersionapi
Versionapi Version stringstring The Storefront API version that the client queries. Defaults to the version that Hydrogen bundles. To send some queries to another version, such as
unstable, create a second client with that version. Type inference always uses Hydrogen's bundled schema. Write your own types for fields outside the bundled schema.- Anchor to cachecachecacheCacheInstanceCacheInstance
The cache that stores query results. The client caches only queries that pass a
cachestrategy. The client never caches mutations, results with GraphQL errors, or responses whoseCache-Controlheader containsprivateorno-store. A response with either directive also makes the final response private when you call, whether or not the query passes acachestrategy.- Anchor to defaultTimeoutInMsdefault
Timeout In Msdefault Timeout In Ms numbernumber How long a request can run before the client throws a
, in milliseconds. Defaults to30000. Set0to turn off the timeout. Stale-while-revalidate refreshes use the same timeout, or 30,000 when the timeout is0.throws an error for a negative value.- Anchor to fetchfetchfetchFetchFetch
The fetch function that the client calls. Defaults to
.throws an error when neither exists.- Anchor to storefrontIdstorefront
Idstorefront Id stringstring Your Hydrogen storefront's ID. The client sends the ID in the
Shopify-Storefront-Idheader of every request.- Anchor to waitUntilwait
Untilwait Until WaitUntilWaitUntil Keeps the runtime alive while the client writes to the cache in the background, such as a worker's
function. Without the function, each cached query waits for its cache write before it resolves.
Anchor to privatenobuyercontextclientoptionsPrivateNoBuyerContextClientOptions
Options for a private client without buyer context, for background jobs, webhooks, and other server code with no customer. The client sends a private access token and no customer IP address.
- Anchor to privateStorefrontTokenprivate
Storefront Tokenprivate Storefront Token stringstringrequiredrequired Your private Storefront API access token. Keep the token out of browser code.
throws an error when the token is missing.- Anchor to storeDomainstore
Domainstore Domain stringstringrequiredrequired Your store's domain, such as
my-store.myshopify.com. Hydrogen addshttps://when the domain has no protocol, and removes trailing slashes.throws an error for an empty domain.- Anchor to apiVersionapi
Versionapi Version stringstring The Storefront API version that the client queries. Defaults to the version that Hydrogen bundles. To send some queries to another version, such as
unstable, create a second client with that version. Type inference always uses Hydrogen's bundled schema. Write your own types for fields outside the bundled schema.- Anchor to cachecachecacheCacheInstanceCacheInstance
The cache that stores query results. The client caches only queries that pass a
cachestrategy. The client never caches mutations, results with GraphQL errors, or responses whoseCache-Controlheader containsprivateorno-store. A response with either directive also makes the final response private when you call, whether or not the query passes acachestrategy.- Anchor to defaultTimeoutInMsdefault
Timeout In Msdefault Timeout In Ms numbernumber How long a request can run before the client throws a
, in milliseconds. Defaults to30000. Set0to turn off the timeout. Stale-while-revalidate refreshes use the same timeout, or 30,000 when the timeout is0.throws an error for a negative value.- Anchor to fetchfetchfetchFetchFetch
The fetch function that the client calls. Defaults to
.throws an error when neither exists.- Anchor to storefrontIdstorefront
Idstorefront Id stringstring Your Hydrogen storefront's ID. The client sends the ID in the
Shopify-Storefront-Idheader of every request.- Anchor to waitUntilwait
Untilwait Until WaitUntilWaitUntil Keeps the runtime alive while the client writes to the cache in the background, such as a worker's
function. Without the function, each cached query waits for its cache write before it resolves.
TypeScript
Examples
Create a public client
Description
Create a module-scoped public client with a static request context. This example sends requests without an access token when `PUBLIC_STOREFRONT_API_TOKEN` is unset.
TypeScript
import { createShopifyRequestContext, createStorefrontClient } from "@shopify/hydrogen"; const requestContext = createShopifyRequestContext({ request: { headers: new Headers() }, i18n: { country: "US", language: "EN" }, }); export const storefront = createStorefrontClient({ type: "public", requestContext, config: { storeDomain: process.env.PUBLIC_STORE_DOMAIN!, publicStorefrontToken: process.env.PUBLIC_STOREFRONT_API_TOKEN, }, });Create a private client per request
Description
Create a private client for the current request. This example reads the trusted `buyerIp` from the `oxygen-buyer-ip` header and throws when the header is missing.
TypeScript
import { createShopifyRequestContext, createStorefrontClient } from "@shopify/hydrogen"; export function createRequestStorefront(request: Request) { const buyerIp = request.headers.get("oxygen-buyer-ip"); if (!buyerIp) throw new Error("oxygen-buyer-ip is required for private clients"); const requestContext = createShopifyRequestContext({ request, i18n: { country: "US", language: "EN" }, buyerIp, }); return createStorefrontClient({ type: "private", requestContext, config: { storeDomain: process.env.PUBLIC_STORE_DOMAIN!, privateStorefrontToken: process.env.PRIVATE_STOREFRONT_API_TOKEN!, }, }); }Configure the client cache
Description
Pass a Web Cache and `waitUntil` in the client config, then opt one query into caching. This example caches a product list query with `Cache.long()`.
TypeScript
import { Cache, createShopifyRequestContext, createStorefrontClient, gql, } from "@shopify/hydrogen"; const PRODUCTS_QUERY = gql(`query { products(first: 10) { nodes { title } } }`); export async function getProducts(request: Request, waitUntil: (promise: Promise<unknown>) => void) { const storefront = createStorefrontClient({ type: "public", requestContext: createShopifyRequestContext({ request, i18n: { country: "US", language: "EN" } }), config: { storeDomain: process.env.PUBLIC_STORE_DOMAIN!, publicStorefrontToken: process.env.PUBLIC_STOREFRONT_API_TOKEN, cache: await caches.open("hydrogen"), waitUntil, }, }); return storefront.graphql(PRODUCTS_QUERY, { cache: Cache.long() }); }
Anchor to Client typesClient types
Anchor to clienttypeClientType
Chooses the kind of Storefront API client to create. Use public in the browser, with a public access token or none. Use private during server-side rendering, with a private token and the customer's IP address. Use in background jobs and webhooks, with a private token and no customer.
"public" | "private" | "private_no_buyer_context""public" | "private" | "private_no_buyer_context"Anchor to publicstorefrontclientPublicStorefrontClient
The type of a client that you create with type: "public".
- Anchor to apiUrlapi
Urlapi Url stringstringrequiredrequired The Storefront API GraphQL endpoint that the client calls.
- Anchor to graphqlgraphqlgraphql<const Doc extends DocLike | string>(doc: Doc, ...options: GqlRestParam<ResolveDoc<Doc>, Extra>) => Promise<StorefrontGraphqlResult<ResolveDoc<Doc>>><const Doc extends DocLike | string>(doc: Doc, ...options: GqlRestParam<ResolveDoc<Doc>, Extra>) => Promise<StorefrontGraphqlResult<ResolveDoc<Doc>>>requiredrequired
Runs a Storefront API query or mutation and returns a typed result. Pass a
gqldocument or a plain query string. When the operation declaresor, the client sets the variable from the request context and overrides any value you pass. Variables with other types stay caller-owned.The method throws an error when a query passes a
cachestrategy and the client has no cache, or when the strategy usesprivatemode. A catch block fordoesn't catch this configuration error. To cache customer-specific data, usewith a key unique to the customer.- Anchor to localelocalelocaleRequestContext["locale"]RequestContext["locale"]requiredrequired
The locale resolved for this request. The client sends its country and language for
$countryand$languagevariables.- Anchor to requestContextrequest
Contextrequest Context RequestContextRequestContextrequiredrequired The request context that you passed to
.- Anchor to storeUrlstore
Urlstore Url stringstringrequiredrequired Your store's URL with its protocol, such as
https://my-store.myshopify.com.- Anchor to typetypetypeTypeTyperequiredrequired
The client type that you passed to
.- Anchor to storefrontIdstorefront
Idstorefront Id stringstring The storefront ID from the client options.
- Anchor to i18ni18ni18nRequestContext["i18n"]RequestContext["i18n"]requiredrequireddeprecateddeprecated
The locale resolved for this request.
DeprecatedUse
localeinstead. Removed in the next major release.Deprecated:Use
localeinstead. Removed in the next major release.
Anchor to privatestorefrontclientPrivateStorefrontClient
The type of a client that you create with type: "private". The client's request context includes .
- Anchor to apiUrlapi
Urlapi Url stringstringrequiredrequired The Storefront API GraphQL endpoint that the client calls.
- Anchor to graphqlgraphqlgraphql<const Doc extends DocLike | string>(doc: Doc, ...options: GqlRestParam<ResolveDoc<Doc>, Extra>) => Promise<StorefrontGraphqlResult<ResolveDoc<Doc>>><const Doc extends DocLike | string>(doc: Doc, ...options: GqlRestParam<ResolveDoc<Doc>, Extra>) => Promise<StorefrontGraphqlResult<ResolveDoc<Doc>>>requiredrequired
Runs a Storefront API query or mutation and returns a typed result. Pass a
gqldocument or a plain query string. When the operation declaresor, the client sets the variable from the request context and overrides any value you pass. Variables with other types stay caller-owned.The method throws an error when a query passes a
cachestrategy and the client has no cache, or when the strategy usesprivatemode. A catch block fordoesn't catch this configuration error. To cache customer-specific data, usewith a key unique to the customer.- Anchor to localelocalelocaleRequestContext["locale"]RequestContext["locale"]requiredrequired
The locale resolved for this request. The client sends its country and language for
$countryand$languagevariables.- Anchor to requestContextrequest
Contextrequest Context RequestContextRequestContextrequiredrequired The request context that you passed to
.- Anchor to storeUrlstore
Urlstore Url stringstringrequiredrequired Your store's URL with its protocol, such as
https://my-store.myshopify.com.- Anchor to typetypetypeTypeTyperequiredrequired
The client type that you passed to
.- Anchor to storefrontIdstorefront
Idstorefront Id stringstring The storefront ID from the client options.
- Anchor to i18ni18ni18nRequestContext["i18n"]RequestContext["i18n"]requiredrequireddeprecateddeprecated
The locale resolved for this request.
DeprecatedUse
localeinstead. Removed in the next major release.Deprecated:Use
localeinstead. Removed in the next major release.
Anchor to requestscopedprivatestorefrontclientRequestScopedPrivateStorefrontClient
The type of a private client with the default request context. Use the type to annotate a private client without naming your request context type.
- Anchor to apiUrlapi
Urlapi Url stringstringrequiredrequired The Storefront API GraphQL endpoint that the client calls.
- Anchor to graphqlgraphqlgraphql<const Doc extends DocLike | string>(doc: Doc, ...options: GqlRestParam<ResolveDoc<Doc>, Extra>) => Promise<StorefrontGraphqlResult<ResolveDoc<Doc>>><const Doc extends DocLike | string>(doc: Doc, ...options: GqlRestParam<ResolveDoc<Doc>, Extra>) => Promise<StorefrontGraphqlResult<ResolveDoc<Doc>>>requiredrequired
Runs a Storefront API query or mutation and returns a typed result. Pass a
gqldocument or a plain query string. When the operation declaresor, the client sets the variable from the request context and overrides any value you pass. Variables with other types stay caller-owned.The method throws an error when a query passes a
cachestrategy and the client has no cache, or when the strategy usesprivatemode. A catch block fordoesn't catch this configuration error. To cache customer-specific data, usewith a key unique to the customer.- Anchor to localelocalelocaleShopifyMatchedLocale<ShopifyI18n>ShopifyMatchedLocale<ShopifyI18n>requiredrequired
The locale resolved for this request. The client sends its country and language for
$countryand$languagevariables.- Anchor to requestContextrequest
Contextrequest Context RequestContextRequestContextrequiredrequired The request context that you passed to
.- Anchor to storeUrlstore
Urlstore Url stringstringrequiredrequired Your store's URL with its protocol, such as
https://my-store.myshopify.com.- Anchor to typetypetypeTypeTyperequiredrequired
The client type that you passed to
.- Anchor to storefrontIdstorefront
Idstorefront Id stringstring The storefront ID from the client options.
- Anchor to i18ni18ni18nShopifyMatchedLocale<ShopifyI18n>ShopifyMatchedLocale<ShopifyI18n>requiredrequireddeprecateddeprecated
The locale resolved for this request.
DeprecatedUse
localeinstead. Removed in the next major release.Deprecated:Use
localeinstead. Removed in the next major release.
ShopifyMatchedLocale
A locale resolved for one request. `pathSegment` is replaced by the derived `pathPrefix` (`""` for the default locale and under domain routing), which is what URL builders consume. Domain-routed locales keep their `hostname` so canonical and `hreflang` URLs can be built.
DistributiveOmit<
ShopifySupportedLocale<TI18n>,
"pathSegment"
> & {
pathPrefix: string;
}DistributiveOmit
T extends unknown ? Omit<T, K> : neverShopifySupportedLocale
Every locale entry a definition can resolve to, keeping any extra per-locale fields.
ShopifySupportedLocale<TI18n>ShopifyI18n
Module-scope internationalization definition shared by the server request context, route matching, URL builders, and client scripts. Create it with `defineShopifyI18n`.
- defaultLocale
Locale used when routing determines nothing: unprefixed paths or unrecognized hostnames.
ShopifyLocale - routing
Omit for single-locale storefronts.
ShopifyI18nRouting
ShopifyLocale
A `{language, country}` pair identifying one locale a storefront serves.
- country
ShopifyCountryCode - language
ShopifyLanguageCode
ShopifyCountryCode
ShopifyLanguageCode
ShopifyI18nRouting
{
type: "pathname";
/**
* Locales served under a prefix. `defaultLocale` is served unprefixed only and must not be
* listed here, so every page has one canonical URL.
*/
locales: readonly ShopifyPathnameLocale[];
} | {
type: "domain";
/**
* Locales served per hostname. `defaultLocale` must be listed here so it has a canonical
* hostname for links and sitemaps; it is also what unrecognized hosts (localhost, preview
* URLs) resolve to.
*/
locales: readonly ShopifyDomainLocale[];
}ShopifyPathnameLocale
A locale served under a URL path prefix. The prefix is derived from the locale as `/{language}-{country}` (lowercased, `_` → `-`), so `{language: "FR", country: "CA"}` is served at `/fr-ca`. Set `pathSegment` when the derived segment is undesirable, for example `PT_BR` + `BR` derives to `pt-br-br`. A segment is a single path part: no slashes.
ShopifyLocale & {
pathSegment?: string;
}ShopifyDomainLocale
A locale served from its own hostname. Match is exact on `URL.hostname` (no port), so `fr.example.com`, `example.fr`, and `example.com` are three separate entries. Aliases such as `www.` are a redirect concern and must not be listed here.
ShopifyLocale & {
hostname: string;
}Anchor to privatenobuyercontextstorefrontclientPrivateNoBuyerContextStorefrontClient
The type of a client that you create with , for background jobs and webhooks.
- Anchor to apiUrlapi
Urlapi Url stringstringrequiredrequired The Storefront API GraphQL endpoint that the client calls.
- Anchor to graphqlgraphqlgraphql<const Doc extends DocLike | string>(doc: Doc, ...options: GqlRestParam<ResolveDoc<Doc>, Extra>) => Promise<StorefrontGraphqlResult<ResolveDoc<Doc>>><const Doc extends DocLike | string>(doc: Doc, ...options: GqlRestParam<ResolveDoc<Doc>, Extra>) => Promise<StorefrontGraphqlResult<ResolveDoc<Doc>>>requiredrequired
Runs a Storefront API query or mutation and returns a typed result. Pass a
gqldocument or a plain query string. When the operation declaresor, the client sets the variable from the request context and overrides any value you pass. Variables with other types stay caller-owned.The method throws an error when a query passes a
cachestrategy and the client has no cache, or when the strategy usesprivatemode. A catch block fordoesn't catch this configuration error. To cache customer-specific data, usewith a key unique to the customer.- Anchor to localelocalelocaleRequestContext["locale"]RequestContext["locale"]requiredrequired
The locale resolved for this request. The client sends its country and language for
$countryand$languagevariables.- Anchor to requestContextrequest
Contextrequest Context RequestContextRequestContextrequiredrequired The request context that you passed to
.- Anchor to storeUrlstore
Urlstore Url stringstringrequiredrequired Your store's URL with its protocol, such as
https://my-store.myshopify.com.- Anchor to typetypetypeTypeTyperequiredrequired
The client type that you passed to
.- Anchor to storefrontIdstorefront
Idstorefront Id stringstring The storefront ID from the client options.
- Anchor to i18ni18ni18nRequestContext["i18n"]RequestContext["i18n"]requiredrequireddeprecateddeprecated
The locale resolved for this request.
DeprecatedUse
localeinstead. Removed in the next major release.Deprecated:Use
localeinstead. Removed in the next major release.
Anchor to CachingCaching
To cache queries, pass a cache in the client config and a Cache strategy in each query's options.