commercetools Frontend Integration

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
Development and maintenance of all types of websites:
Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1 servicesAll 2065 services
commercetools Frontend Integration
Medium
~5 business days
FAQ
Our competencies:
Development stages
Latest works
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    822
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    847
  • image_website-sbh_0.png
    Website development for SBH Partners
    999
  • image_website-_0.png
    Website development for Red Pear
    451

Integrating commercetools with Frontend

commercetools has no ready-made UI — only API. Frontend is built on any stack, but the most mature ecosystem evolved around Next.js + @commercetools/platform-sdk. Alternative — Composable Commerce Frontend (formerly Frontastic), but it adds its own abstraction layer.

SDK and Client Initialization

npm install @commercetools/platform-sdk @commercetools/sdk-client-v2 \
  @commercetools/sdk-middleware-auth @commercetools/sdk-middleware-http \
  @commercetools/sdk-middleware-queue

Three clients for three contexts:

// lib/ctpClient.ts
import { createClient } from "@commercetools/sdk-client-v2";
import { createApiBuilderFromCtpClient } from "@commercetools/platform-sdk";

function buildClient(authMiddleware: Middleware) {
  return createApiBuilderFromCtpClient(
    createClient({
      middlewares: [
        authMiddleware,
        createQueueMiddleware({ concurrency: 5 }),
        createHttpMiddleware({
          host: `https://api.${process.env.CTP_REGION}.commercetools.com`,
        }),
      ],
    })
  ).withProjectKey({ projectKey: process.env.CTP_PROJECT_KEY! });
}

export const serverApiRoot = buildClient(
  createAuthMiddlewareForClientCredentialsFlow({
    host: `https://auth.${process.env.CTP_REGION}.commercetools.com`,
    projectKey: process.env.CTP_PROJECT_KEY!,
    credentials: {
      clientId: process.env.CTP_SERVER_CLIENT_ID!,
      clientSecret: process.env.CTP_SERVER_CLIENT_SECRET!,
    },
    scopes: [`view_products:${process.env.CTP_PROJECT_KEY}`],
  })
);

Server-side client is used in getStaticProps / RSC. Client-side (with user token) — only in browser.

Next.js: Static Catalog Generation

// app/catalog/[slug]/page.tsx (App Router)
import { serverApiRoot } from "@/lib/ctpClient";

export async function generateStaticParams() {
  const products = await serverApiRoot
    .productProjections()
    .get({
      queryArgs: {
        limit: 500,
        staged: false,
        where: 'masterData(published = true)',
      },
    })
    .execute();

  return products.body.results.map((p) => ({ slug: p.slug["ru"] }));
}

export default async function ProductPage({
  params,
}: {
  params: { slug: string };
}) {
  const result = await serverApiRoot
    .productProjections()
    .get({
      queryArgs: {
        where: `slug(ru = "${params.slug}")`,
        expand: ["productType", "categories[*]"],
        priceCurrency: "RUB",
        priceChannel: "channel-key=storefront-ru",
      },
    })
    .execute();

  const product = result.body.results[0];
  if (!product) notFound();

  return <ProductDetail product={product} />;
}

For frequently updated catalogs — ISR with revalidate: 300.

Cart: Client State + API

Cart is stored in commercetools — cartId is saved in cookie. No duplication in localStorage.

// hooks/useCart.ts
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { browserApiRoot } from "@/lib/ctpClientBrowser";
import Cookies from "js-cookie";

export function useCart() {
  const queryClient = useQueryClient();
  const cartId = Cookies.get("cart_id");

  const { data: cart } = useQuery({
    queryKey: ["cart", cartId],
    queryFn: async () => {
      if (!cartId) return null;
      return (await browserApiRoot.carts().withId({ ID: cartId }).get().execute()).body;
    },
    enabled: !!cartId,
  });

  const addToCart = useMutation({
    mutationFn: async ({
      productId,
      variantId,
      quantity,
    }: {
      productId: string;
      variantId: number;
      quantity: number;
    }) => {
      if (!cartId) {
        const newCart = await browserApiRoot.carts().post({
          body: {
            currency: "RUB",
            store: { typeId: "store", key: "web-ru" },
            lineItems: [{ productId, variantId, quantity }],
          },
        }).execute();
        Cookies.set("cart_id", newCart.body.id, { expires: 30 });
        return newCart.body;
      }

      return (await browserApiRoot.carts().withId({ ID: cartId }).post({
        body: {
          version: cart!.version,
          actions: [{ action: "addLineItem", productId, variantId, quantity }],
        },
      }).execute()).body;
    },
    onSuccess: (updatedCart) => {
      queryClient.setQueryData(["cart", updatedCart.id], updatedCart);
    },
  });

  return { cart, addToCart };
}

Search with Algolia Sync

commercetools doesn't provide full-text search with Algolia-level relevance. Productive solution — sync via Subscriptions:

// subscriptions/algolia-sync.ts
// Commercetools Subscription → SQS → Lambda → Algolia

export async function handler(event: SQSEvent) {
  for (const record of event.Records) {
    const message = JSON.parse(record.body);
    const { notificationType, resourceTypeId, resourceUserProvidedIdentifiers } = message;

    if (resourceTypeId !== "product") continue;

    const product = await serverApiRoot
      .products()
      .withId({ ID: message.resource.id })
      .get({ queryArgs: { expand: ["productType"] } })
      .execute();

    if (notificationType === "ResourceDeleted") {
      await algoliaIndex.deleteObject(message.resource.id);
    } else {
      await algoliaIndex.saveObject(transformForAlgolia(product.body));
    }
  }
}

Customer Authentication

// app/api/auth/login/route.ts (Next.js Route Handler)
export async function POST(req: Request) {
  const { email, password } = await req.json();

  try {
    const customerClient = buildCustomerClient(email, password);
    const me = await customerClient.me().get().execute();

    const token = await getCustomerToken(email, password);

    const response = NextResponse.json({ customer: me.body });
    response.cookies.set("ct_token", token.access_token, {
      httpOnly: true,
      secure: true,
      maxAge: token.expires_in,
    });
    response.cookies.delete("cart_id"); // merging anonymous cart

    return response;
  } catch {
    return NextResponse.json({ error: "Invalid credentials" }, { status: 401 });
  }
}

Common Integration Errors

  • 409 ConcurrentModification — current version not provided. Solution: retry with fresh object fetch
  • 400 InvalidInput on cart — triggered Extension rejected operation, read extensionExtraInfo
  • Prices not displayedpriceCurrency and priceChannel not passed in request
  • Slug not found — product not published (staged: true instead of false)

Performance and Caching

  • RSC + fetch with next: { tags: ['products'] } → on-demand revalidation via webhook
  • For high-load catalogs — Redis cache on top of SDK requests
  • Images via commercetools CDN (cdn.commercetools.com) with transformations via query params