Customer account client
The createCustomerAccountClient function creates a server-only GraphQL client for the Customer Account API. Use the client with gql to query a signed-in customer's profile, orders, and other account data with typed results.
Import createCustomerAccountClient and gql from @shopify/hydrogen/customer-account.
Get the customer's access token from createCustomerSession, and pass the token with each graphql() call.
Anchor to API clientAPI client
Creates a client that sends Customer Account API requests from your server. Create the client with the current request's context.
The function throws when the shop ID, API version, or timeout is invalid, when the request context has no HTTPS URL, when no fetch implementation is available, and when the function runs in a browser.
- Anchor to input1input1input1CreateCustomerAccountClientOptionsCreateCustomerAccountClientOptionsrequiredrequired
The shop ID, the API version, the request context, a custom fetch, and the request timeout.
A client with the GraphQL endpoint URL and a
graphql()method for Customer Account API requests.
CreateCustomerAccountClientOptions
Options for creating a Customer Account API client.
- customerApiVersion
Customer Account API version in `YYYY-MM` format. Defaults to `2026-10`.
string - defaultTimeoutInMs
Timeout for each request in milliseconds. Must be a positive integer no greater than 2,147,483,647. Defaults to `30000`.
number - fetch
Custom fetch implementation. Defaults to the global fetch.
{ (input: RequestInfo | URL, init?: RequestInit): Promise<Response>; (input: string | Request | URL, init?: RequestInit): Promise<Response>; } - requestContext
The context for the current request, from `createShopifyRequestContext`. The context's URL must use HTTPS, or creating the client throws. Local `http://` URLs on localhost, 127.0.0.1, and ::1 also work for development. The client fills `$language: LanguageCode` from the context's language and stops requests when the context's signal aborts.
ShopifyRequestContext - shopId
Numeric Shopify shop ID as a string of digits, such as `12345`.
string
ShopifyRequestContext
The context for one request. Pass the context to Hydrogen's API clients and route handlers for that request.
ShopifyRequestContextBase & {
/** The locale resolved for this request, with the path prefix it is served under. */
locale: RequestLocale<TI18n>;
/**
* The locale resolved for this request.
* @deprecated Use `locale` instead. Removed in the next major release.
*/
i18n: RequestLocale<TI18n>;
}ShopifyRequestContextBase
The fields and methods on every request context.
- __hydrogenShopifyRequestContextBrand
A type-only marker. Create request contexts only with `createShopifyRequestContext`.
never - applyResponseHeaders
Adds the headers that a Hydrogen storefront needs to the final response. Call the method on each response that your app builds. Responses from `handleShopifyRoutes` and `handleShopifyRedirects` already carry these headers. Append your committed session headers before you call the method. The method makes any response that sets a cookie private and uncacheable. The method also sets the `powered-by` header, makes responses marked with `markResponseAsPersonalized()` private and uncacheable, and adds eligible Shopify cookies only to non-document responses for methods other than `GET` and `HEAD`.
(headers: Headers) => void - applyStorefrontRequestHeaders
Adds the Hydrogen SDK headers and the customer's cookie, privacy, and origin headers to a Storefront API request. The Storefront API client and the API proxies call the method for you.
(headers: Headers) => void - buyerIp
The customer's trusted IP address. Private Storefront API clients require it.
string - captureSubrequestHeaders
Saves the cookies from the first Storefront API response that sets cookies. The Storefront API client calls the method for you, and `applyResponseHeaders()` can add the cookies to your response.
(headers: Headers) => void - consumeStorefrontResponseHeaders
Saves the cookies from a proxied Storefront API response and removes the `set-cookie` header from that response. The API proxies in `handleShopifyRoutes` call the method for you.
(headers: Headers) => void - cookie
The incoming request's `Cookie` header. Hydrogen forwards the header to the Storefront API.
string - getForwardedRequestHeaders
Returns the incoming request's headers with Shopify's request headers added. Pass the headers when you forward the request to a proxy or another origin.
() => Headers - i18nDefinition
The i18n definition the context matched its locale against. Absent for the deprecated fixed-locale input.
ShopifyI18n - markResponseAsPersonalized
Marks the final response as private and uncacheable because the response holds customer data, such as a server-rendered cart. `applyResponseHeaders()` then sets `Cache-Control: private, no-store, max-age=0, must-revalidate` and removes `Surrogate-Control` and every vendor `*-Cache-Control` header. Call the method before `applyResponseHeaders()`, and only on requests whose response holds customer data, so other responses stay cacheable. Pass a short `reason` that names the customer data. The Customer Account API client and the customer session call the method for you.
(reason: string) => void - markResponseAsSessionEstablishing
Lets the final response set Shopify cookies before the customer has a Shopify session, and marks the response as private and uncacheable. The UCP MCP proxy calls the method for you.
(reason: string) => void - requestGroupId
The ID that groups this request's Shopify API calls. Hydrogen reads the ID from the request headers or generates one.
string - signal
The incoming request's abort signal. Hydrogen's API clients stop their requests when the signal aborts.
AbortSignal - storefrontOrigin
The origin of the incoming request's URL. Hydrogen forwards the origin to the Storefront API.
string - url
The incoming request's URL.
string
Headers
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;
}RequestLocale
The locale a request context resolves: matched from a definition, or the legacy fixed locale.
TI18n extends ShopifyI18n
? ShopifyMatchedLocale<TI18n>
: TI18n extends I18nConfig
? NormalizedI18nConfig<TI18n>
: neverShopifyMatchedLocale
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>I18nConfig
Deprecated: a fixed request locale with an optional path prefix. Removed in the next major release.
- country
The request's country.
ShopifyCountryCode - language
The request's language.
ShopifyLanguageCode - pathPrefix
The URL prefix for localized routes, such as `/es-es`. Hydrogen adds the prefix to standard route redirects and product variant URLs.
string
NormalizedI18nConfig
Omit<TConfig, "pathPrefix"> & {
pathPrefix: string;
}CustomerAccountClient
A client that sends Customer Account API requests from your server for the current request.
- apiUrl
The GraphQL endpoint, `https://shopify.com/{shopId}/account/customer/api/{version}/graphql`.
string - graphql
Sends a Customer Account API query or mutation with the customer's access token, and returns the data, any GraphQL errors, and the response headers. Pass a document from the Customer Account `gql` function. The request makes the final response private and uncacheable when you call `applyResponseHeaders()`. When the document declares `$language: LanguageCode` and you omit it, the client fills the variable from the request context's language. A `$language` variable of any other type stays yours. The method throws a `TypeError` for a document from any other `gql` function, including the Storefront API `gql` function, and for variables that aren't an object. When a signal aborts, the method throws the signal's reason. A missing or malformed access token throws `CustomerAccountAuthenticationError`, a timeout throws `CustomerAccountTimeoutError`, and other request failures throw `CustomerAccountApiError`.
<const Doc extends AnyCustomerAccountDocument>(document: Doc, ...options: CustomerAccountGqlRestParam<Doc>) => Promise<CustomerAccountGraphqlResult<ResultOfDoc<Doc>>>
AnyCustomerAccountDocument
Any Customer Account API document. Use the type as a constraint when a function accepts any document.
CustomerAccountDocument<unknown, never, string>CustomerAccountDocument
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;
}CustomerAccountGqlRestParam
The options argument for a Customer Account API request. Pass `variables` when the document declares a required variable other than `$language: LanguageCode`. TypeScript reports an error when a required variable is missing.
HasNoRequiredKeys<UserVariables<Doc>> extends true
? [options: CustomerAccountGraphqlOptions<UserVariables<Doc>>]
: [
options: CustomerAccountGraphqlOptions<UserVariables<Doc>> & {
variables: UserVariables<Doc>;
},
]HasNoRequiredKeys
Resolves to `true` when an object type has no required keys.
Record<string, never> extends T ? true : falseUserVariables
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 : neverI18nVariableNamesOfDoc
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
: neverI18nVariableTypes
typeof CUSTOMER_ACCOUNT_I18N_VARIABLE_TYPESCustomerAccountGraphqlOptions
Options for a single Customer Account API request.
- accessToken
The customer's access token, such as one from the customer session's `getOrRefreshAccessToken()` method.
string - signal
Stops this request when the signal aborts. The request also stops when the request context's signal aborts or the timeout passes.
AbortSignal - variables
The document's variables. When the document declares `$language: LanguageCode` and you omit it, the client fills the variable from the request context's language. A `$language` variable of any other type stays yours.
Variables
CustomerAccountGraphqlResult
Result of a Customer Account API request. Check `errors` to tell the outcomes apart. On success, `data` holds the result and `errors` is `undefined`. When the response has GraphQL errors, `errors` holds them and `data` can be `null`. Every result includes the raw response headers.
{ data: Result; errors?: undefined; headers: Headers } | { data: Result | null; errors: GraphQLFormattedError[]; headers: 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>
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
TypeScript
Examples
Query the current customer
Description
Fetch the customer's name and email with the Customer Account API client. This example returns `null` when the response has GraphQL errors.
TypeScript
import type { ShopifyRequestContext } from "@shopify/hydrogen"; import { createCustomerAccountClient, gql } from "@shopify/hydrogen/customer-account"; const CUSTOMER_QUERY = gql(` query CurrentCustomer { customer { firstName lastName emailAddress { emailAddress } } } `); export async function getCustomer( shopId: string, requestContext: ShopifyRequestContext, accessToken: string, ) { const customerAccount = createCustomerAccountClient({ shopId, requestContext }); const result = await customerAccount.graphql(CUSTOMER_QUERY, { accessToken }); if (result.errors) return null; return result.data.customer; }
Anchor to Typed queries and mutationsTyped queries and mutations
Creates a typed Customer Account API query or mutation from a GraphQL source string. Pass the document to the Customer Account API client. Call gql as a regular function.
Pass an array of fragment documents as the second argument to append the fragments to the operation. Each fragment must come from this gql function, or the call throws a .
To validate documents, run hydrogen gql check in your typecheck script with the setup. Framework typecheck commands don't validate the documents.
Anchor to gql-parametersParameters
- Anchor to sourcesourcesourcestringstringrequiredrequired
The GraphQL source of an operation or a fragment.
- Anchor to fragmentsfragmentsfragmentsreadonly AnyCustomerAccountDocument[]readonly AnyCustomerAccountDocument[]
The fragment documents that the operation uses.
Anchor to gql-returnsReturns
A typed document to pass to the Customer Account API client.
TypeScript
Examples
Define a customer query
Description
Define a query for the customer's name and email address with `gql`. The client returns typed results for the query.
TypeScript
import { gql } from "@shopify/hydrogen/customer-account"; export const CUSTOMER_QUERY = gql(` query CustomerDetails { customer { firstName lastName emailAddress { emailAddress } } } `);Compose a query with fragments
Description
Add an order fragment to a query for the customer's first 10 orders. This example passes the fragment as the second argument to `gql`.
TypeScript
import { gql } from "@shopify/hydrogen/customer-account"; const ORDER_FIELDS = gql(` fragment OrderFields on Order { id totalPrice { amount currencyCode } } `); export const ORDERS_QUERY = gql( ` query CustomerOrders { customer { orders(first: 10) { nodes { ...OrderFields } } } } `, [ORDER_FIELDS], );