Catalyst Client
The Catalyst Client is how a Catalyst storefront calls BigCommerce’s GraphQL Storefront API. Import the instance your project configures:
The client builds request URLs, sets request headers, and parses JSON responses for you. It’s published as the @bigcommerce/catalyst-client npm package, and your project configures an instance of it in client/index.ts, using the store hash, storefront token, and channel ID from your environment variables.
Client configuration
client/index.ts creates the client with createClient(). You can change these options to adjust how every request is made:
There’s no hook that runs after a response is received. To act on failures, use onError or catch the errors that fetch() throws.
Methods
-
fetch(): runs any query or mutation in the GraphQL Storefront API. -
fetchSitemapIndex(channelId?: string): fetches the XML sitemap index (/xmlsitemap.php) for a channel and returns it as text. When you omitchannelId, it uses the same channel resolution asfetch().
Fetch
The following sections describe the fetch() method.
Parameters
Request headers
The fetch method automatically sets the following headers:
"Content-Type": "application/json""Authorization": "Bearer <storefrontToken>""User-Agent": <backendUserAgent>"X-Bc-Customer-Access-Token": <customerAccessToken>(whencustomerAccessTokenis provided)"X-Bc-Error-On-Invalid-Customer-Access-Token": "true"(whenvalidateCustomerAccessTokenistrue)"X-BC-Trusted-Proxy-Secret": <secret>(when theBIGCOMMERCE_TRUSTED_PROXY_SECRETenvironment variable is set)
Catalyst’s beforeRequest hook in client/index.ts also adds:
"Accept-Language": <locale>(when the current locale is known)"X-Forwarded-For"and"True-Client-IP", set to the shopper’s IP address, and"X-Correlation-ID". These are added only to uncached requests (cache: 'no-store'orcache: 'no-cache'), because request headers are part of the Next.js Data Cache key, and per-request values would make every cached lookup miss.
Headers you pass in fetchOptions.headers override any of these.
Retries
Queries that fail with a 502, 503, or 504 response, or with a network error such as a dropped connection, are retried up to two more times, after 100 ms and then 300 ms. Each retry logs a warning. Mutations are never retried, because they aren’t safe to repeat.
Return value
The fetch method returns a promise that resolves to a response object containing the requested data. The response follows the structure defined in the GraphQL query.
-
Return Type:
Promise<BigCommerceResponse<TResult>>The
BigCommerceResponsetype wraps the actual data returned from the API, whereTResultrepresents the expected shape of the response data.Inside
BigCommerceResponse, thedatafield holds the actual data returned by the GraphQL API, which matches the structure of the query or mutation you executed. -
Errors: the method throws when the HTTP request fails, or when the API returns GraphQL errors that the
errorPolicysays to throw. See Error handling.
Examples
Get customer orders (authenticated request)
Get product reviews (unauthenticated request)
The example output in the console:
To flatten edges and node wrappers, use the removeEdgesAndNodes() utility exported by @bigcommerce/catalyst-client.
Error handling
fetch() checks the HTTP response for you and throws if something goes wrong, so wrap calls in try/catch rather than inspecting the response. @bigcommerce/catalyst-client exports these error classes:
Before throwing a GraphQL error, the client calls its onError hook. By default, Catalyst’s hook redirects the shopper to sign out when a query fails with a BigCommerceAuthError, so an expired customer session is cleared automatically.
Logging
You can log the request’s operation name, type, and execution time to the console, along with the query complexity.
Logging is on by default outside production, and off in production. To change this, set the CLIENT_LOGGER environment variable to true or false. When logging is enabled, the fetch method invokes the requestLogger() function internally to capture and log the information.