Custom integrations with commercetools Frontend include both backend and frontend development:
- Backend extension API: consists of a default export with the required
actions,data-sources, anddynamic-page-handlermethods merged with the other required integrations. - Frontend SDK integration: consumes and utilizes the
@commercetools/frontend-sdkpackage to call backend actions and handle events.
You must develop actions on the backend extension so that frontend SDK integrations can call them. For ease of development and debugging, we recommended developing the backend extension and frontend integration at the same time.
Create the SDK integration
packages/PROJECT_NAME/frontend/src/sdk. If this folder does not exist, your project might predate the addition of the commercetools Frontend SDK. In such cases, refer to the installation and setup instructions for the coFE SDK.@commercetools/frontend-sdk) package dependency up to date with the latest release. Updating the base SDK ensures you have access to the latest features and enhancements. After you complete the integration, you do not need to continuously update the dependency, however, we recommend you periodically check for new features, improvements, and bug fixes.Implement the SDK integration
Integration abstract class, which is imported from @commercetools/frontend-sdk.Integration abstract class also defines the CustomEvents generic type to extend the BaseEvents type, which is of type Events.Even if you don't need to define any custom events for an SDK integration, we recommend you create and export an empty type from your integration to let you define custom events in the future. If you don't create types for your custom events, compilation errors will occur. Failure to export this type will also cause errors when adding event handlers for these events, and when adding triggers within your SDK integration.
Cart from the coFE domain types at packages/PROJECT_NAME/types. For complete type-safety, the commerce types should be mapped to the domain types on the backend.import {
SDK,
Integration,
SDKResponse,
ServerOptions,
} from '@commercetools/frontend-sdk';
import { Cart } from '@types/cart/Cart';
/**
* Define a type for the integration's custom events, this will be exported
* from the project index along with the integration. This type is used in
* the generic argument of the SDK and Integration.
*/
type MyCustomEvents = {
emptyCartFetched: { cartId: string };
};
/**
* Define a type for the payload your action will take, this will be sent
* in the body of the request (optional).
*/
type MyFirstActionPayload = {
account: {
email: string;
};
};
/**
* Define a type for the query your action will take, this will be appended to
* the URL of the request (optional).
*/
type MyFirstActionQuery = {
name: string;
};
/**
* Define a type for the action, typing this action takes advantage of the
* generic nature of the SDK's callAction method and lets the user know the
* return type.
*/
type MyFirstAction = (
payload: MyFirstActionPayload,
query: MyFirstActionQuery,
options: { serverOptions?: ServerOptions } = {}
) => Promise<SDKResponse<Cart>>;
/**
* Define the class and extend the SDK's abstract Integration class, passing
* along the MyCustomEvents type
*/
class MyIntegration extends Integration<MyCustomEvents> {
/**
* Define your action, ensuring explicit types, this will tell the user
* the return type and required parameters, using the generic behavior
* of the callAction method on the SDK.
*/
private myFirstAction: MyFirstAction = (
payload: MyFirstActionPayload,
query: MyFirstActionQuery,
options: { serverOptions?: ServerOptions } = {}
) => {
/**
* Return the call of the SDK callAction method by passing the
* action name (the path to the backend action), the payload,
* the query, and serverOptions to support SSR cookie handling.
*/
return this.sdk.callAction({
actionName: 'example/myAction',
payload,
query,
serverOptions: options.serverOptions,
});
};
// Define the type of the example domain object.
example: {
myFirstAction: MyFirstAction;
};
/**
* Define the constructor with the SDK singleton as an argument,
* passing the MyCustomEvents type again.
*/
constructor(sdk: SDK<MyCustomEvents>) {
// Call the super method on the abstract class, passing it the SDK.
super(sdk);
/**
* Initialize any objects with defined methods. This pattern
* improves user experience for complex integrations because actions
* are called in the format sdk.<integration>.<domain>.<name>.
*/
this.example = {
myFirstAction: this.myFirstAction,
};
}
}
// Export the integration to be imported and exported in the package index.
export { MyIntegration, MyCustomEvents };
In this code example:
-
The
MyCustomEventstype is based on the base SDK'sEvents. In practice, we recommended you to define the type in another file for readability reasons. -
The
MyFirstActionPayloadtype defines the action's optional payload argument. This type defines what must be passed into the integration's action call, which is serialized into the body of the request. It must be an object of typeAcceptedPayloadTypes. -
The
MyFirstActionQuerytype defines the action's optional query argument. It must be an object of typeAcceptedQueryTypes, which accepts any serializable JSON type. This query is appended to the URL of the action call. Following the example, it would be<endpoint>/frontastic/example/myAction?name=<nameValue>. -
The
MyFirstActiontype defines the type of the action function. The parameters typed with theMyFirstActionPayloadandMyFirstActionQueryarguments, and the return type ofPromise<SDKResponse<Cart>>are specified. By specifying the return ofSDKResponsewith theCartgeneric argument, the generic argument of the SDK'scallActionmethod is defined and made type-safe. This way, the integration user knows on a successful action call they will have a return type of{ isError: false, data: Cart }. -
The
MyIntegrationclass extends the base SDK'sIntegrationabstract class, and passes theMyCustomEventstype to the generic argument. This lets you trigger and/or add event handlers for custom events as well as the base SDK'sStandardEventscommerce types. To interact with another integration's custom events, you must import its events and add the type to the generic argument with an intersection. -
The
myFirstActionfunction is defined with theMyFirstActiontype. The function is marked as private so it cannot be called directly on the class. However, in practice, this will likely be defined elsewhere and set up externally. For an example on how these actions can be set up, see the constructor of the Composable Commerce integration within your project atpackages/PROJECT_NAME/frontend/sdk/composable-commerce/library/Integration.ts, orpackages/PROJECT_NAME/frontend/src/sdk/composable-commerce-b2b/library/Integration.tsfor B2B projects. \On the return of this method, the SDK'scallActionmethod is returned, passing theactionName,payload, andquery. TheactionNamewill match the backend's default export action structure, foractionName: 'example/myAction'the default export will call the following action on the backend.export default { 'dynamic-page-handler': { ... }, 'data-sources': { ... }, actions: { example: { myAction: <function to be called> } } } -
The type of the
exampleobject is defined, where the methods for the actions in theexampledomain are also defined. Structuring the methods in this way creates a tree structure for callable methods. For example, a typical commerce integration might haveaccount,cart,product, andwishlistdomains for actions. Therefore, by structuring the methods in this way, it is easier to find the methods to be called. An example of the domain can be found in thecomposable-commerceintegration in theCartActions. -
The
constructoris defined with thesdksingleton passing theMyCustomEventsas a generic argument. This lets you trigger and/or add event handlers for custom events as well as the base SDK'sBaseEvents. To interact with another integration's custom events, you must import its events and add the type to the generic argument with an intersection. Then, thesuperkeyword is used to invoke the constructor of the abstract base class passing it thesdk. Finally, the example domain object is set up with thethis.myFirstActionmethod definition. -
The
MyIntegrationandMyCustomEventstypes are exported and imported to the package's index file. From there, they are exported to be imported into your commercetools Frontend project.
Promise<SDKResponse<Cart>>. The response from the SDK can be of following types:SDKResponsetype from the base SDK.{ isError: false, data: T }on success, where theTtype is generic and defines the type of data fetched on success, which you can specify by passing the type to the SDK’scallActionmethod (sdk.callAction<T>) as the generic argument.{ isError: true, error: FetchError }on error.
composable-commerce integration.Implement event handling
The commercetools Frontend SDK comes with the event engine that lets integrations add event handlers and communicate with other integrations by triggering events.
Add and remove event handlers
on and off methods. First, the
emptyCartFetched event handler callback is defined. Then in the
useEffect React lifecycle hook, the on method is called on component mounting. Finally, a function calling the
off method on component unmounting is returned to clean up.emptyCartFetched named function is defined to serve as the eventHander parameter. The event argument type of Event<EventName, EventData> must be fully typed for the SDK to accept the handler argument along with "emptyCartFetched" as the value of the eventName parameter.const emptyCartFetched = (
event: Event<
'emptyCartFetched',
{
cartId: string;
}
>
) => {
// Access event.data.cartId in the body of the event handler.
};
useEffect(() => {
sdk.on('emptyCartFetched', emptyCartFetched);
return () => {
sdk.off('emptyCartFetched', emptyCartFetched);
};
}, []);
off method is called within the cleanup function of useEffect. Without this cleanup, the handler would be added each time the component mounts, potentially causing memory leaks or unintended behavior.For event handlers that should persist beyond a single component's lifecycle, such as those tied to the lifespan of the application, integration users can call the
on method within the SDK template constructor. To attach persistent handlers directly within the SDK integration, call the on method in the SDK integration’s constructor and pass an anonymous function.Trigger custom events
trigger method. First, the
getCart action is defined, for which a response is returned by the sdk. Then, the
isError parameter is checked to see if the action has errored and the trigger method is called to trigger the standard cartFetched event. Finally, if the cart is empty, the
trigger method is called to trigger the emptyCartFetched event.getCart: async () => {
const response = await sdk.callAction<Cart>({
actionName: 'cart/getCart',
});
if (response.isError === false) {
sdk.trigger(
new Event({
eventName: 'cartFetched',
data: {
cart: response.data,
},
})
);
if (!response.data.lineItems || response.data.lineItems.length === 0) {
sdk.trigger(
new Event({
eventName: 'emptyCartFetched',
data: {
cartId: response.data.cartId,
},
})
);
}
}
return response;
};
response.isError must be explicitly compared to the boolean value in non-strict projects for the narrowing to work on the SDKResponse union type. Otherwise, the error Property 'data' does not exist on type will occur on when accessing response.data. For our default strict projects, a simple truthy/falsy comparison such as !response.isError is sufficient.https://github.com/FrontasticGmbH/frontend-sdk/blob/master/src/types/sdk/SDKResponse.ts