Catalyst Client

Catalyst allows you to retrieve info from BigCommerce's APIs through the Catalyst Client.

import { client } from '~/client';

The client simplifies what you need to do to handle requests and responses. For example, you don't need to construct request URLs, configure request headers, or parse JSON responses. The client uses the channel ID and authorization tokens configured in the .env file by default.

Methods

Fetch

The following sections describe the fetch() method.

Parameters

Parameter nameTypeRequired?Description
documentobject DocumentDecoration<TResult, TVariables>YesThe GraphQL query or mutation you want to execute. It must be in the form of a string or a GraphQL AST (Abstract Syntax Tree) that defines the query.

The DocumentDecoration interface supports types from @graphql-typed-document-node/core and TypedQueryDocumentNode. These ensure the types of variables and results match. The document could be a GraphQL query or mutation.
variablesobject TVariablesNoVariables to be passed to the GraphQL query or mutation.
customerAccessTokenstringNoThe customer's access token for authenticated requests.

This token is required for operations that need customer authentication (e.g., accessing cart, checkout, orders, or customer data) and can be populated with the getSessionCustomerAccessToken() utility function. The token is added as an X-Bc-Customer-Access-Token header.
fetchOptionsobject FetcherRequestInitNoCustom options for the fetch request.

FetcherRequestInit extends the global RequestInit interface in JavaScript, which includes parameters such as method, headers, body, and options for caching and credentials.
channelIdstringNoAllows you to specify a different storefront channel for the request.

Defaults to the channel ID in the .env file.
errorPolicynone | auth | ignore | allNo- none (default): The client will throw any errors that are returned from the API. This is useful for ensuring you properly catch errors provided through the API.

- auth: The client will throw an error if there are any authorization issues, for example, a missing or invalid Customer Access Token.

- ignore: The client will ignore any errors and will just return the data.

- all (advance): The client will return the full response with the data, including any errors returned from the API. This advance option lets you customize what happens with the response.
validateCustomerAccessTokenbooleanNo- true (default): The client will pass a header to the API to return any auth related errors, for example a missing or invalid Customer Access Token.

- false: This option should be set when making a request that has customer-specific information, but it shouldn't throw an error. For example, a query to fetch the guest vs. shopper categories in the header.

Request headers

The fetch method automatically sets the following headers:

  • "Content-Type": "application/json"
  • "User-Agent": <backendUserAgent>
  • "X-Bc-Customer-Access-Token": <customerAccessToken> (when customerAccessToken is provided)
  • "X-Bc-Error-On-Invalid-Customer-Access-Token": <validateCustomerAccessToken> (when validateCustomerAccessToken is true)

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 BigCommerceResponse type wraps the actual data returned from the API, where TResult represents the expected shape of the response data.

    Inside BigCommerceResponse, the data field holds the actual data returned by the GraphQL API, which matches the structure of the query or mutation you executed.

  • Error Handling:

    If the response is not ok (i.e., the request fails), the method throws a BigCommerceAPIError, which includes the HTTP status and any GraphQL errors returned in the response.

Examples

Get customer orders (authenticated request)

import { client } from '~/client';
import { graphql } from '~/client/graphql';
import { getSessionCustomerAccessToken } from '~/auth';
 
const GET_CUSTOMER_ORDERS = graphql(`
  query getCustomerOrders {
    customer {
      orders {
        edges {
          node {
            entityId
            orderNumber
            status
          }
        }
      }
    }
  }
`);
 
const customerAccessToken = await getSessionCustomerAccessToken();
 
const response = await client.fetch({
  document: GET_CUSTOMER_ORDERS,
  customerAccessToken,
  fetchOptions: customerAccessToken ? { cache: 'no-store' } : { next: { revalidate } },
});
 

Get product reviews (unauthenticated request)

import { client } from '~/client';
import { graphql } from '~/client/graphql'; // A utility function for handling GraphQL queries
 
const GET_PRODUCT_REVIEWS_QUERY = graphql(`
  query getProductReviews($productIds: [Int!]) {
    site {
      products(entityIds: $productIds) {
        edges {
          node {
            reviews {
              edges {
                node {
                  author {
                    name
                  }
                  title
                  text
                }
              }
            }
          }
        }
      }
    }
  }
`);
 
const response = await client.fetch({
  document: GET_PRODUCT_REVIEWS_QUERY, // GraphQL query
  variables: { productIds: [101, 202] },  // Query variables
  fetchOptions: { cache: 'no-store' }, // Optional fetch options
});
 
console.log(response.data);

The example output in the console:

{
  "site": {
    "products": [
      {
        "reviews": {
          "edges": [
            {
              "node": {
                "author": {
                  "name": "John Doe"
                },
                "title": "Great product",
                "text": "This product exceeded my expectations!"
              }
            },
            {
              "node": {
                "author": {
                  "name": "Jane Smith"
                },
                "title": "Good value",
                "text": "Worth the price, very satisfied."
              }
            }
          ]
        }
      }
    ]
  }
}

Error handling

The BigCommerceAPIError class provides error handling and is instantiated when the fetch fails.

if (!response.ok) {
  throw await BigCommerceAPIError.createFromResponse(response);
}

Logging

You can log the request's operation name, type, and execution time to the console, along with the query complexity (opens in a new tab).

To use this feature, enable logging through the CLIENT_LOGGER environment variable. When you run the fetch method, it will invoke the requestLogger() function internally to capture and log the information.