commercetools TypeScript SDK

Description

Core commercetools API and SDK patterns — TypeScript SDK setup, ClientBuilder authentication, project data model (products, customers, orders, types, channels, stores), GraphQL vs REST patterns, query predicates, optimistic concurrency, rate limits, and platform observability. Foundational layer that storefront, MC app, Connect, and integration skills all reference. Use for any commercetools project regardless of surface.

Installation

Recommended: install the full commercetools plugin. It includes this Skill, every other commercetools Skill, our pre-tuned Subagents, and the commercetools Knowledge MCP — which gives AI live access to the commercetools docs, GraphQL/OpenAPI schemas, and query validation. You only install once; every Skill on this site becomes available in every session.
Install the plugin

In any Claude Code session, run the following commands one at a time:

  1. Add the commercetools AI marketplace:

    /plugin marketplace add commercetools/commercetools-ai-plugins
    
  2. Install the commercetools AI plugin (Skills + Subagents + MCP):

    /plugin install commercetools@commercetools
    
Reload plugins

If you've updated the plugin or installed it in another window and need the current session to pick up the latest version:

/reload-plugins
Claude Desktop
Customize -> Personal plugins -> Create plugin -> Add marketplace -> Add commercetools/commercetools-ai-plugins. Then, click on the plugin and click Install.

Instructions Included

SKILL.md

commercetools TypeScript SDK

Foundational patterns for connecting to the commercetools API from TypeScript. These patterns are project-type agnostic — they apply whether you are building a Next.js storefront, a serverless function, or a CLI script.

Workflow

When this skill is invoked, always follow these steps:

  1. Docs search (required, run first) — The first time you use this skill in a session you must run this before answering. It gathers the latest verified documentation as your primary grounding, filtered to the products this skill covers. Use this script for documentation search while working with this skill; the Knowledge MCP covers everything else. Always confirm details against retrieved documentation rather than the skill text alone:
    node "<this skill's directory>/scripts/docs-search.mjs" \
      --query "<extract key terms from user's question>" \
      --app-name "<host app: claude-code, claude-chat, cursor, codex, copilot — or the host's own name>" \
      --model "<current-model>" \
      --commercetools-project-key "<if known>" \
      --commercetools-region "<if known>" \
      --limit 10
    
    Pass the commercetools project key and region (as in api.{region}.commercetools.com) only if already in your context; otherwise omit both. Never search files or ask the user for them.
  2. Combine with skill references — Cross-reference the analysis output with local references in ./references/ for complete context.
  3. Provide implementation guidance — Synthesize the documentation with the specific integration mode the user is targeting.

Optional scripts

Fetch GraphQL schema — Run this when you need context about a commercetools GraphQL query or mutation — for example, to inspect a resource's fields, types, and available operations before writing a query, or to verify a GraphQL query/mutation you have just generated against the real schema. It fetches the partial GraphQL SDL for a single commercetools resource:
node scripts/graphql-schemata.mjs \
  --resource-name "<commercetools resource, e.g. Cart, Product, Order>" \
  --app-name "<host app: claude-code, claude-chat, cursor, codex, copilot — or the host's own name>" \
  --model "<current-model>"
The output is the GraphQL SDL for that resource. If the resource name is not recognized, the script prints the list of valid resource names — pick the correct one and re-run. Note: the SDL may contain stubbed types — referenced resources rendered as stubs, with their real type name given in a comment. Fetch any you need separately by re-running this script with that type name as --resource-name.
Fetch OpenAPI (REST) schema — Run this when you need context about a commercetools REST endpoint, request/response payload, or update action — for example, to inspect a resource's REST operations before constructing a request, or to verify a REST request/payload you have just generated against the real specification. It fetches the partial OpenAPI specification for a single commercetools resource:
node scripts/openApi-schemata.mjs \
  --resource-name "<commercetools resource, e.g. api-Cart-write, api-Customer-read, checkout-Application>" \
  --app-name "<host app: claude-code, claude-chat, cursor, codex, copilot — or the host's own name>" \
  --model "<current-model>"
The output is the OpenAPI specification (YAML) for that resource. REST resources use a read/write-split naming form (e.g. api-Cart-read, api-Cart-write). If the resource name is not recognized, the script prints the list of valid resource names — pick the correct one and re-run. Note: the spec does not include reference-expansion schemas — fetch a referenced resource's schema separately by re-running this script with that resource as --resource-name.

SDK Setup

See sdk-setup.md for:
  • Package installation (@commercetools/platform-sdk + @commercetools/ts-client)
  • ClientBuilder singleton with Client Credentials flow
  • Required environment variables and auth URLs by region
  • Required API client scopes

Product Search API

  • Official docs and why the legacy productProjections search is deprecated
  • Full-text + filter + sort + facets example
  • Category filter, SKU lookup, price selection, discount expansion, BOPIS channel filtering

References

product-search.md

Product Search API

Impact: HIGH — The Product Projection Search endpoint (productProjections().search()) is deprecated and lacks facets and proper variant matching. Always use the Product Search API, and fetch price and locale data through the GraphQL productsSearch query, not the deprecated productProjectionParameters option.

Table of Contents


INCORRECT:
// Deprecated — no facets, no proper variant matching
await apiRoot.productProjections().search().get({ queryArgs: { ... } }).execute();
CORRECT:
// Product Search API — use this always
await apiRoot.products().search().post({ body: { ... } }).execute();
The Product Search API uses a POST body for the query, not URL query args.

Pattern 2: Strong Typing — Never Use any or unknown

INCORRECT: casting to any or unknown to work around missing types.
// BAD — loses all type safety
const id = (result as any).id;
const discount = (ctPrice.discounted?.discount?.obj as any)?.name;
CORRECT: import and use the SDK types from @commercetools/platform-sdk directly.
import type {
  ProductSearchResult,
  ProductVariant,
  Price as CtPrice,
  ProductDiscount,
  LocalizedString,
} from '@commercetools/platform-sdk';

// Result typing — Product Search returns IDs; fetch the Product data separately (Patterns 4–7)
const result: ProductSearchResult = body.results[0];
const productId: string = result.id;

// Expanded discount reference (Product Projections API with `expand`) — obj is typed as ProductDiscount | undefined
const discountObj = ctPrice.discounted?.discount?.obj as ProductDiscount | undefined;
const discountName = getLocalizedString(discountObj?.name as LocalizedString | undefined, locale);
The @commercetools/platform-sdk exports types for every resource, reference, and expanded object in the API. Search the package exports before reaching for any.

Pattern 3: Full Example — Text + Filter + Sort + Facets

import { apiRoot } from './client';
import type { ProductSearchRequest } from '@commercetools/platform-sdk';

const searchRequest: ProductSearchRequest = {
  query: {
    and: [
      {
        fullText: {
          field: 'name',
          language: 'en-US', // Always use BCP-47
          value: 'cotton shirt',
        },
      },
      {
        filter: [
          {
            exact: {
              field: 'variants.attributes.color',
              fieldType: 'ltext',
              language: 'en-US', // Always use BCP-47
              value: 'Blue',
            },
          },
        ],
      },
    ],
  },
  sort: [
    { field: 'name', language: 'en-US', order: 'asc' },
  ],
  facets: [
    {
      distinct: {
        name: 'categories',
        field: 'categories.id',
      },
    },
    {
      distinct: {
        name: 'sizes',
        field: 'variants.attributes.size',
        fieldType: 'enum',
      },
    },
    {
      ranges: {
        name: 'price-ranges',
        field: 'variants.prices.centAmount',
        ranges: [
          { from: 0,    to: 2000 },
          { from: 2000, to: 5000 },
          { from: 5000 },
        ],
      },
    },
  ],
  markMatchingVariants: true,
  limit: 20,
  offset: 0,
};

const { body } = await apiRoot.products().search().post({ body: searchRequest }).execute();
// body.results[].id — Product IDs; fetch the Product data with the GraphQL productsSearch query (Patterns 4–7)
// body.facets — array of ProductSearchFacetResult - ask commercetools-developer-tips about ProductSearchFacetResult
// body.total, body.offset, body.limit — for pagination

Pattern 4: Category Filter

Filter to products in a category and all its subcategories using categoriesSubTree. Use the GraphQL productsSearch query so the matching Products come back in the same request, with price selection and locale projection applied:
query CategoryProducts($categoryId: String!, $currency: Currency!, $country: Country!, $locale: Locale!) {
  productsSearch(
    query: { exact: { field: "categoriesSubTree", value: $categoryId } }
    limit: 24
    offset: 0
  ) {
    total
    results {
      id
      product(localesProjection: [$locale]) {
        masterData {
          current {
            name(locale: $locale)
            masterVariant {
              sku
              price(currency: $currency, country: $country) {
                value { currencyCode centAmount fractionDigits }
              }
            }
          }
        }
      }
    }
  }
}
const { body } = await apiRoot.graphql().post({
  body: { query: CATEGORY_PRODUCTS, variables: { categoryId, currency: 'USD', country: 'US', locale: 'en-US' } },
}).execute();
Use categoriesSubTree instead of categories — categories matches only the exact category, not descendants.

Pattern 5: SKU Lookup

Fetch a single product by exact SKU match:

query ProductBySku($sku: String!, $currency: Currency!, $country: Country!, $locale: Locale!) {
  productsSearch(
    query: { exact: { field: "variants.sku", value: $sku } }
    limit: 1
  ) {
    results {
      id
      product(localesProjection: [$locale]) {
        masterData {
          current {
            name(locale: $locale)
            masterVariant {
              sku
              price(currency: $currency, country: $country) {
                value { currencyCode centAmount fractionDigits }
              }
            }
          }
        }
      }
    }
  }
}
results is empty when the SKU doesn't exist — call notFound() in the page.

Pattern 6: Price Selection

INCORRECT: passing productProjectionParameters in the search request body. It is deprecated (announced 11 December 2025) and will be removed.
CORRECT: pass currency and country to the price field of the Product Data you fetch through productsSearch. commercetools applies price selection and returns the price for that currency/country combination.
price(currency: "EUR", country: "DE") {
  value { currencyCode centAmount fractionDigits }
}
# price is now the EUR price for Germany — no client-side filtering needed
To project Prices by Store, pass storeProjection to the product field. See Locale and Store projection.
If you cannot use GraphQL, use the Product Search result IDs to query the Product Projections API with priceCurrency and priceCountry.

Pattern 7: Discount Expansion

GraphQL resolves references, so there is nothing to expand. Select the discount name through discounted.discount:
price(currency: $currency, country: $country) {
  value { currencyCode centAmount fractionDigits }
  discounted {
    value { currencyCode centAmount fractionDigits }
    discount { name(locale: $locale) }
  }
}
Map the result to your own price type from the generated GraphQL types, not any:
function mapPrice(price: PriceFragment): Price {
  return {
    value: mapMoney(price.value),
    discounted: price.discounted
      ? {
          value:        mapMoney(price.discounted.value),
          discountName: price.discounted.discount.name ?? undefined,
        }
      : undefined,
  };
}
If you use the Product Projections API instead, add expand=masterVariant.price.discounted.discount and expand=variants[*].price.discounted.discount to the query, otherwise discount is just { id: '...' } and the obj field is absent.

Checklist

  • Using apiRoot.products().search().post() — never productProjections().search().get()
  • No any or unknown casts — types imported from @commercetools/platform-sdk
  • Category pages filter with categoriesSubTree, not categories
  • No productProjectionParameters (deprecated) — currency + country passed to the price field of productsSearch for correct price selection
  • SKU lookup uses exact: { field: 'variants.sku', value: sku }
  • markMatchingVariants: true set when variant-level filtering is active
  • discounted { discount { name } } selected when rendering discount names or badges
sdk-setup.md

commercetools SDK Setup

Impact: CRITICAL — One ClientBuilder instance per process. Instantiating it per request causes token exhaustion and memory leaks.

Table of Contents


Pattern 1: Install Packages

npm install @commercetools/platform-sdk @commercetools/ts-client
PackagePurpose
@commercetools/platform-sdkTyped commercetools REST API client — apiRoot, request builders, SDK types
@commercetools/ts-clientToken management + HTTP middleware (ClientBuilder, withClientCredentialsFlow)

Pattern 2: SDK Client Singleton

INCORRECT: new ClientBuilder() inside a page, component, Route Handler, or lambda invocation — creates a new HTTP client and OAuth token per call.
CORRECT — one module-level singleton, imported everywhere:
// lib/ct/client.ts
import { createApiBuilderFromCtpClient } from '@commercetools/platform-sdk';
import { ClientBuilder } from '@commercetools/ts-client';

const projectKey = process.env.CTP_PROJECT_KEY!;
const authUrl    = process.env.CTP_AUTH_URL!;
const apiUrl     = process.env.CTP_API_URL!;

function buildClient() {
  return new ClientBuilder()
    .withProjectKey(projectKey)
    .withClientCredentialsFlow({
      host: authUrl,
      projectKey,
      credentials: {
        clientId:     process.env.CTP_CLIENT_ID!,
        clientSecret: process.env.CTP_CLIENT_SECRET!,
      },
      scopes: [process.env.CTP_SCOPES!],
    })
    .withHttpMiddleware({ host: apiUrl })
    .build();
}

export const apiRoot = createApiBuilderFromCtpClient(buildClient())
  .withProjectKey({ projectKey });

export { projectKey, apiUrl, authUrl };
withClientCredentialsFlow handles OAuth 2.0 token fetching and auto-refresh transparently — you never call the auth endpoint directly.
Every helper function imports apiRoot from this file:
import { apiRoot } from './client';

export async function getSomething(id: string) {
  const { body } = await apiRoot.things().withId({ ID: id }).get().execute();
  return body;
}

Pattern 3: Environment Variables

INCORRECT: In Next.js, NEXT_PUBLIC_CTP_CLIENT_SECRET — exposes the secret in the browser bundle.
CORRECT — all commercetools variables are server-only (no NEXT_PUBLIC_ prefix):
# .env  (add to .gitignore — never commit)
CTP_PROJECT_KEY=your-project-key
CTP_AUTH_URL=https://auth.{region}.commercetools.com
CTP_API_URL=https://api.{region}.commercetools.com
CTP_CLIENT_ID=your-client-id
CTP_CLIENT_SECRET=your-client-secret
# B2C example
CTP_SCOPES=manage_order_edits:your-project-key view_sessions:your-project-key view_product_selections:your-project-key view_shipping_methods:your-project-key manage_shopping_lists:your-project-key view_discount_codes:your-project-key manage_customers:your-project-key view_types:your-project-key manage_sessions:your-project-key manage_orders:your-project-key view_standalone_prices:your-project-key view_tax_categories:your-project-key view_published_products:your-project-key view_cart_discounts:your-project-key create_anonymous_token:your-project-key view_project_settings:your-project-key view_products:your-project-key view_categories:your-project-key
Auth URL by region:
RegionAuth URL
Americas (GCP)https://auth.us-central1.gcp.commercetools.com
Europe (GCP)https://auth.europe-west1.gcp.commercetools.com
Australia (GCP)https://auth.australia-southeast1.gcp.commercetools.com
Required API client scopes (Merchant Center → Settings → Developer Settings): Use Frontend B2C template (or Frontend B2B), then make sure manage_sessions and manage_orders are included.

Checklist

  • lib/ct/client.ts exports a single apiRoot — no new ClientBuilder() anywhere else
  • .env is listed in .gitignore
  • No commercetools env vars exposed to client rendering component
  • All lib/ct/*.ts helper functions import apiRoot from ./client