Skip to main content

CMSClient

The CMSClient is the main entry point for all client-side CMS functionality. It handles the connection to the backend and delegates methods to the configured adapter.

Usage

You must create a new instance of CMSClient and provide it to your application using the CMSClientProvider.

// 1. Create the client
const CMSClient = new CMSClient({
adapter: CommerceCMSAdapter,
api,
previewOptions: {
authorizedUrls: ['localhost:9002'],
scriptPath: '/public/webApplicationInjector.js'
}
});

// 2. Provide the client to your app
<CMSClientProvider client={CMSClient}>
<AppRoutes />
</CMSClientProvider>

CMSClientOptions

NameTypeDescriptionDefault
adapterCMSAdapterThe adapter to use for backend communication.Required
apiCreateApiThe API instance for the adapter to make requests.Required
cacheTimenumberHow long CMS data should be kept in the cache (in ms).300000 (5 minutes)
previewOptionsPreviewOptionsOptions to configure the preview system (e.g., for SmartEdit).Optional

PreviewOptions Interface

ParameterTypeDescription
authorizedUrlsstring[]A list of authorized URLs allowed for preview.
scriptPathstringThe path to the script used to connect the storefront to the preview system (e.g., SmartEdit's Web Application Injector).

Deep Dive

Description: The CMSClient acts as the central orchestrator for all client-side CMS operations. It holds the configuration and state, abstracting the specific implementation details of the CMSAdapter away from the UI components.

  • How To: A single instance of CMSClient should be created and provided at the root of your application. Hooks like usePage and useCMSClient will then access this single instance via React's context.

    // Correct: Instantiate once and provide globally.
    // src/shop/client/api/creators/cms.ts
    export default new CMSClient({
    adapter: CommerceCMSAdapter,
    api
    });

    // src/shop/client/components/App.tsx
    <CMSClientProvider client={CMSClient}>
    {/* ... */}
    </CMSClientProvider>
  • Best Practice: Avoid creating multiple instances of CMSClient or instantiating it within a React component. Doing so would lead to unnecessary re-renders, loss of state, and multiple data fetches. The client is designed to be a singleton within the application's lifecycle.

    // Avoid: Instantiating the client inside a component.
    function MyComponent() {
    const client = new CMSClient({ adapter: CommerceCMSAdapter, api }); // Don't do this!
    // ...
    }