create Storefront Clientutility
The function creates helpers that enable you to quickly query the Shopify Storefront API.
When used on the server, it is recommended to use the prop. When used on the client, it is recommended to use the
prop or consider using
instead.
- Anchor to propspropsrequired
- getShopifyDomain(props?: Partial<Pick<, "storeDomain">>) => string
Creates the fully-qualified URL to your myshopify.com domain.
By default, it will use the config you passed in when calling
. However, you can override the following settings on each invocation of
:
- getStorefrontApiUrl(props?: Partial<Pick<, "storeDomain" | "storefrontApiVersion">>) => string
Creates the fully-qualified URL to your store's GraphQL endpoint.
By default, it will use the config you passed in when calling
. However, you can override the following settings on each invocation of
:
-
- getPrivateTokenHeaders(props?: Partial<Pick<, "contentType">> & Pick<, "privateStorefrontToken"> & { buyerIp?: string; }) => Record<string, string>
Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the private Server-to-Server token which reduces the chance of throttling but must not be exposed to clients. Server-side calls should prefer using this over
.
By default, it will use the config you passed in when calling
. However, you can override the following settings on each invocation of
:
-
-
Note that
defaults to what you configured in
and defaults to
'json'
, but a specific call may require usinggraphql
. When usingon the
body
, use'json'
; otherwise, use'graphql'
.- getPublicTokenHeaders(props?: Partial<Pick<, "contentType">> & Pick<, "publicStorefrontToken">) => Record<string, string>
Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the public token which increases the chance of throttling but also can be exposed to clients. Server-side calls should prefer using
.
By default, it will use the config you passed in when calling
. However, you can override the following settings on each invocation of
:
-
Note that
defaults to what you configured in
and defaults to
'json'
, but a specific call may require usinggraphql
. When usingon the
body
, use'json'
; otherwise, use'graphql'
.
StorefrontClientReturn
CreateStorefrontClientGeneratedType
The `createStorefrontClient()` function creates helpers that enable you to quickly query the Shopify Storefront API. When used on the server, it is recommended to use the `privateStorefrontToken` prop. When used on the client, it is recommended to use the `publicStorefrontToken` prop.
- props
StorefrontClientProps
StorefrontClientReturn
export function createStorefrontClient(
props: StorefrontClientProps,
): StorefrontClientReturn {
const {
storeDomain,
privateStorefrontToken,
publicStorefrontToken,
storefrontApiVersion = SFAPI_VERSION,
contentType,
} = props;
if (!storeDomain) {
throw new Error(
H2_PREFIX_ERROR +
`\`storeDomain\` is required when creating a new Storefront client.\nReceived "${storeDomain}".`,
);
}
if (storefrontApiVersion !== SFAPI_VERSION) {
warnOnce(
`The Storefront API version that you're using is different than the version this build of Hydrogen React is targeting.` +
`\nYou may run into unexpected errors if these versions don't match. Received verion: "${storefrontApiVersion}"; expected version "${SFAPI_VERSION}"`,
);
}
// only warn if not in a browser environment
if (__HYDROGEN_DEV__ && !privateStorefrontToken && !globalThis.document) {
warnOnce(
`Using a private storefront token is recommended for server environments.` +
`\nRefer to the authentication https://shopify.dev/api/storefront#authentication documentation for more details.`,
);
}
// only warn if in a browser environment and you're using the privateStorefrontToken
if (__HYDROGEN_DEV__ && privateStorefrontToken && globalThis.document) {
warnOnce(
'You are attempting to use a private token in an environment where it can be easily accessed by anyone.' +
'\nThis is a security risk; please use the public token and the `publicStorefrontToken` prop',
);
}
const isMockShop = (domain: string): boolean => domain.includes('mock.shop');
const getShopifyDomain: StorefrontClientReturn['getShopifyDomain'] = (
overrideProps,
) => {
const domain = overrideProps?.storeDomain ?? storeDomain;
return domain.includes('://') ? domain : `https://${domain}`;
};
return {
getShopifyDomain,
getStorefrontApiUrl(overrideProps): string {
const domain = getShopifyDomain(overrideProps);
const apiUrl = domain + (domain.endsWith('/') ? 'api' : '/api');
if (isMockShop(domain)) return apiUrl;
return `${apiUrl}/${
overrideProps?.storefrontApiVersion ?? storefrontApiVersion
}/graphql.json`;
},
getPrivateTokenHeaders(overrideProps): Record<string, string> {
if (
!privateStorefrontToken &&
!overrideProps?.privateStorefrontToken &&
!isMockShop(storeDomain)
) {
throw new Error(
H2_PREFIX_ERROR +
'You did not pass in a `privateStorefrontToken` while using `createStorefrontClient()` or `getPrivateTokenHeaders()`',
);
}
if (__HYDROGEN_DEV__ && !overrideProps?.buyerIp) {
warnOnce(
'It is recommended to pass in the `buyerIp` property which improves analytics and data in the admin.',
);
}
const finalContentType = overrideProps?.contentType ?? contentType;
return {
// default to json
'content-type':
finalContentType === 'graphql'
? 'application/graphql'
: 'application/json',
'X-SDK-Variant': 'hydrogen-react',
'X-SDK-Variant-Source': 'react',
'X-SDK-Version': storefrontApiVersion,
'Shopify-Storefront-Private-Token':
overrideProps?.privateStorefrontToken ?? privateStorefrontToken ?? '',
...(overrideProps?.buyerIp
? {'Shopify-Storefront-Buyer-IP': overrideProps.buyerIp}
: {}),
};
},
getPublicTokenHeaders(overrideProps): Record<string, string> {
if (
!publicStorefrontToken &&
!overrideProps?.publicStorefrontToken &&
!isMockShop(storeDomain)
) {
throw new Error(
H2_PREFIX_ERROR +
'You did not pass in a `publicStorefrontToken` while using `createStorefrontClient()` or `getPublicTokenHeaders()`',
);
}
const finalContentType =
overrideProps?.contentType ?? contentType ?? 'json';
return getPublicTokenHeadersRaw(
finalContentType,
storefrontApiVersion,
overrideProps?.publicStorefrontToken ?? publicStorefrontToken ?? '',
);
},
};
}
StorefrontClientProps
- storeDomain
The host name of the domain (eg: `{shop}.myshopify.com`).
string
- privateStorefrontToken
The Storefront API delegate access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) and [delegate access token](https://shopify.dev/apps/auth/oauth/delegate-access-tokens) documentation for more details.
string
- publicStorefrontToken
The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details.
string
- storefrontApiVersion
The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details.
string
- contentType
Customizes which `"content-type"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `"json"`. When fetching with a `body` that is a plain string, use `"graphql"`. Defaults to `"json"` Can also be customized on a call-by-call basis by passing in `'contentType'` to both `getPrivateTokenHeaders({...})` and `getPublicTokenHeaders({...})`, for example: `getPublicTokenHeaders({contentType: 'graphql'})`
"json" | "graphql"
{
/** The host name of the domain (eg: `{shop}.myshopify.com`). */
storeDomain: string;
/** The Storefront API delegate access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) and [delegate access token](https://shopify.dev/apps/auth/oauth/delegate-access-tokens) documentation for more details. */
privateStorefrontToken?: string;
/** The Storefront API access token. Refer to the [authentication](https://shopify.dev/api/storefront#authentication) documentation for more details. */
publicStorefrontToken?: string;
/** The Storefront API version. This should almost always be the same as the version Hydrogen React was built for. Learn more about Shopify [API versioning](https://shopify.dev/api/usage/versioning) for more details. */
storefrontApiVersion?: string;
/**
* Customizes which `"content-type"` header is added when using `getPrivateTokenHeaders()` and `getPublicTokenHeaders()`. When fetching with a `JSON.stringify()`-ed `body`, use `"json"`. When fetching with a `body` that is a plain string, use `"graphql"`. Defaults to `"json"`
*
* Can also be customized on a call-by-call basis by passing in `'contentType'` to both `getPrivateTokenHeaders({...})` and `getPublicTokenHeaders({...})`, for example: `getPublicTokenHeaders({contentType: 'graphql'})`
*/
contentType?: 'json' | 'graphql';
}
StorefrontClientReturn
- getShopifyDomain
Creates the fully-qualified URL to your myshopify.com domain. By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`: - `storeDomain`
(props?: Partial<Pick<StorefrontClientProps, "storeDomain">>) => string
- getStorefrontApiUrl
Creates the fully-qualified URL to your store's GraphQL endpoint. By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`: - `storeDomain` - `storefrontApiVersion`
(props?: Partial<Pick<StorefrontClientProps, "storeDomain" | "storefrontApiVersion">>) => string
- getPrivateTokenHeaders
Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the private Server-to-Server token which reduces the chance of throttling but must not be exposed to clients. Server-side calls should prefer using this over `getPublicTokenHeaders()`. By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPrivateTokenHeaders({...})`: - `contentType` - `privateStorefrontToken` - `buyerIp` Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.
(props?: Partial<Pick<StorefrontClientProps, "contentType">> & Pick<StorefrontClientProps, "privateStorefrontToken"> & { buyerIp?: string; }) => Record<string, string>
- getPublicTokenHeaders
Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the public token which increases the chance of throttling but also can be exposed to clients. Server-side calls should prefer using `getPublicTokenHeaders()`. By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`: - `contentType` - `publicStorefrontToken` Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.
(props?: Partial<Pick<StorefrontClientProps, "contentType">> & Pick<StorefrontClientProps, "publicStorefrontToken">) => Record<string, string>
{
/**
* Creates the fully-qualified URL to your myshopify.com domain.
*
* By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getShopifyDomain({...})`:
*
* - `storeDomain`
*/
getShopifyDomain: (
props?: Partial<Pick<StorefrontClientProps, 'storeDomain'>>,
) => string;
/**
* Creates the fully-qualified URL to your store's GraphQL endpoint.
*
* By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getStorefrontApiUrl({...})`:
*
* - `storeDomain`
* - `storefrontApiVersion`
*/
getStorefrontApiUrl: (
props?: Partial<
Pick<StorefrontClientProps, 'storeDomain' | 'storefrontApiVersion'>
>,
) => string;
/**
* Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the private Server-to-Server token which reduces the chance of throttling but must not be exposed to clients. Server-side calls should prefer using this over `getPublicTokenHeaders()`.
*
* By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPrivateTokenHeaders({...})`:
*
* - `contentType`
* - `privateStorefrontToken`
* - `buyerIp`
*
* Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.
*/
getPrivateTokenHeaders: (
props?: OverrideTokenHeaderProps &
Pick<StorefrontClientProps, 'privateStorefrontToken'> & {
/**
* The client's IP address. Passing this to the Storefront API when using a server-to-server token will help improve your store's analytics data.
*/
buyerIp?: string;
},
) => Record<string, string>;
/**
* Returns an object that contains headers that are needed for each query to Storefront API GraphQL endpoint. This method uses the public token which increases the chance of throttling but also can be exposed to clients. Server-side calls should prefer using `getPublicTokenHeaders()`.
*
* By default, it will use the config you passed in when calling `createStorefrontClient()`. However, you can override the following settings on each invocation of `getPublicTokenHeaders({...})`:
*
* - `contentType`
* - `publicStorefrontToken`
*
* Note that `contentType` defaults to what you configured in `createStorefrontClient({...})` and defaults to `'json'`, but a specific call may require using `graphql`. When using `JSON.stringify()` on the `body`, use `'json'`; otherwise, use `'graphql'`.
*/
getPublicTokenHeaders: (
props?: OverrideTokenHeaderProps &
Pick<StorefrontClientProps, 'publicStorefrontToken'>,
) => Record<string, string>;
}
Example code
Client Example in NextJS
examples
Example code
description
I am the default example
Client Example in NextJS
import {createStorefrontClient} from '@shopify/hydrogen-react'; export const client = createStorefrontClient({ storeDomain: 'https://{store-name}.myshopify.com', storefrontApiVersion: '2023-10', privateStorefrontToken: '{private token for server-side requests}', }); // in another file where you need to make queries, for example in NextJS server-side: // a Storefront API query const GRAPHQL_QUERY = ` query { shop { name } } `; // make the request export async function getServerSideProps() { // Get the Storefront API url const response = await fetch(client.getStorefrontApiUrl(), { body: JSON.stringify({ query: GRAPHQL_QUERY, }), // Generate the headers using the private token. Additionally, you can pass in the buyer's IP address from the request object to help prevent bad actors from overloading your store. headers: client.getPrivateTokenHeaders({buyerIp: '...'}), method: 'POST', }); if (!response.ok) { throw new Error(response.statusText); } const json = await response.json(); return {props: json}; }