@commercetools/ts-client

中文文档
5.2.0发布于 2026/11/02MITTypeScriptESM + CJS构建来源已验证近 30 天下载 65.8万

commercetools TypeScript SDK client.

原始使用文档

commercetools (Improved) TypeScript SDK client

This is the new and improved Typescript SDK client.

Usage examples

npm install --save @commercetools/ts-client
npm install --save @commercetools/platform-sdk

or

yarn add @commercetools/ts-client
yarn add @commercetools/platform-sdk
import {
  type Next,
  type HttpMiddlewareOptions,
  type AuthMiddlewareBaseOptions,
  type ClientRequest,
  type MiddlewareRequest,
  type MiddlewareResponse,
  type Client,
  createHttpMiddleware,
  createConcurrentModificationMiddleware,
  createAuthMiddlewareForClientCredentialsFlow,
  ClientBuilder,
} from '@commercetools/ts-client'
import { createApiBuilderFromCtpClient } from '@commercetools/platform-sdk'

const projectKey = 'mc-project-key'
const authMiddlewareOptions = {
  host: 'https://auth.europe-west1.gcp.commercetools.com',
  projectKey,
  credentials: {
    clientId: 'mc-client-id',
    clientSecret: 'mc-client-secrets',
  },
  oauthUri: '/oauth/token', // - optional: custom oauthUri
  scopes: [`manage_project:${projectKey}`],
  httpClient: fetch,
}

const httpMiddlewareOptions = {
  host: 'https://api.europe-west1.gcp.commercetools.com',
  httpClient: fetch,
}

const retryOptions = {
  maxRetries: 3,
  retryDelay: 200,
  backoff: true,
  retryCodes: [503],
}

const loggerFn = (response) => {
  // log response object
  console.log(response)
}

// custom middleware
function middleware(options) {
  return (next: Next) =>
    async (request: MiddlewareRequest): Promise<MiddlewareResponse> => {
      const { response, ...rest } = request

      // other actions can also be carried out here e.g logging,
      // error handling, injecting custom headers to http requests etc.
      console.log({ response, rest })
      return next({ ...request })
    }
}

const client: Client = new ClientBuilder()
  .withPasswordFlow(authMiddlewareOptions)
  .withLoggerMiddleware({ loggerFn })
  .withCorrelationIdMiddleware({
    generate: () => 'fake-correlation-id' + Math.floor(Math.random() + 2),
  })
  .withHttpMiddleware(httpMiddlewareOptions)
  .withMiddleware(middleware({})) // <<<------------------- add the custom middleware here
  .build()

const apiRoot = createApiBuilderFromCtpClient(client)

// calling the commercetools `api` functions
// get project details
apiRoot
  .withProjectKey({ projectKey })
  .get()
  .execute()
  .then((x) => {
    /*...*/
  })

// create a productType
apiRoot
  .withProjectKey({ projectKey })
  .productTypes()
  .post({
    body: { name: 'product-type-name', description: 'some description' },
  })
  .execute()
  .then((x) => {
    /*...*/
  })

// create a product
apiRoot
  .withProjectKey({ projectKey })
  .products()
  .post({
    body: {
      name: { en: 'our-great-product-name' },
      productType: {
        typeId: 'product-type',
        id: 'some-product-type-id',
      },
      slug: { en: 'some-slug' },
    },
  })
  .execute()
  .then((x) => {
    /*...*/
  })

Create a client

To create a client, use the ClientBuilder class. The ClientBuilder class provides a fluent API to configure the client.

const authMiddlewareOptions = {
  credentials: {
    clientId: 'xxx',
    clientSecret: 'xxx',
  },
  host: 'https://auth.europe-west1.gcp.commercetools.com',
  projectKey: 'xxx',
}

const httpMiddlewareOptions = {
  host: 'https://api.europe-west1.gcp.commercetools.com',
  httpClient: fetch,
}

const client = new ClientBuilder()
  .withHttpMiddleware(httpMiddlewareOptions)
  .withConcurrentModificationMiddleware()
  .withClientCredentialsFlow(authMiddlewareOptions)
  .build()

The withMiddleware method can be used to add middleware functions (both built-in and custom middleware) in an ordered fashion.

// Example
const authMiddlewareOptions = {
  credentials: {
    clientId: 'xxx',
    clientSecret: 'xxx',
  },
  host: 'https://auth.europe-west1.gcp.commercetools.com',
  projectKey: 'xxx',
}

const httpMiddlewareOptions = {
  host: 'https://api.europe-west1.gcp.commercetools.com',
  httpClient: fetch,
}

const logger = () => {
  return (next) => async (request) => {
    // log request object
    console.log('Request:', request)
    const response = await next(request)

    // log response object
    console.log('Response', response)
    return response
  }
}

const client = new ClientBuilder()
  .withMiddleware(
    createAuthMiddlewareForClientCredentialsFlow(authMiddlewareOptions)
  )
  .withMiddleware(createHttpMiddleware(httpMiddlewareOptions))
  .withMiddleware(createConcurrentModificationMiddleware())
  .withMiddleware(logger())
  .build()

This will add the middleware in an ordered fashion starting with the:

  1. createAuthMiddlewareForClientCredentialsFlow
  2. createHttpMiddleware
  3. createConcurrentModificationMiddleware
  4. logger

Note that when using the withMiddleware function to add a custom middleware along side other in built middleware functions, it will add the custom middleware to the start of the execution chain.

// Example
const authMiddlewareOptions = {
  credentials: {
    clientId: 'xxx',
    clientSecret: 'xxx',
  },
  host: 'https://auth.europe-west1.gcp.commercetools.com',
  projectKey: 'xxx',
}

const httpMiddlewareOptions = {
  host: 'https://api.europe-west1.gcp.commercetools.com',
  httpClient: fetch,
}

const logger = () => {
  return (next) => async (request) => {
    // log request object
    console.log('Request:', request)
    const response = await next(request)

    // log response object
    console.log('Response', response)
    return response
  }
}

const client = new ClientBuilder()
  .withClientCredentialsFlow(authMiddlewareOptions)
  .withHttpMiddleware(httpMiddlewareOptions)
  .withConcurrentModificationMiddleware()
  .withMiddleware(logger())
  .build()

The order of execution is as follows:

  1. withMiddleware <------ the custom middleware
  2. withClientCredentialsFlow
  3. withHttpMiddleware
  4. withConcurrentModificationMiddleware

版本与发布记录

@commercetools/ts-client 共发布 68 个版本,首次发布于 2022/12/15;过去 12 个月发布了 14 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
5.2.0latest2026/11/028 天前
5.1.12026/10/101 个月前
5.1.02026/10/051 个月前
5.0.32026/09/151 个月前
5.0.22026/08/073 个月前
5.0.12026/08/053 个月前

其他发布通道:next → 2.1.0-alpha.1。

关于 @commercetools/ts-client 的常见问题

@commercetools/ts-client 是什么?

commercetools TypeScript SDK client.

如何安装 @commercetools/ts-client?

在项目目录运行 npm install @commercetools/ts-client,或使用 pnpm add / yarn add / bun add。

@commercetools/ts-client 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@commercetools/ts-client 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@commercetools/ts-client 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@commercetools/ts-client 可以商用吗?

@commercetools/ts-client 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@commercetools/ts-client 的下载量有多少?

根据 npm 官方下载统计,@commercetools/ts-client 在 2026/10/11 – 2026/11/09 这 30 天内被下载 657,977 次,日均约 21,933 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@commercetools/ts-client 还在维护吗?

最新版本 5.2.0 发布于 2026/11/02(8 天前);至今共发布 68 个版本,其中过去 12 个月发布了 14 个;首次发布于 2022/12/15。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。