Set up the TypeScript SDK

Learn how to configure your environment for the TypeScript SDK.

Ask about this Page
Copy for LLM
View as Markdown

After completing this module, you should be able to:

  • Use the TypeScript SDK to work on a commercetools Project.

The following instructions help you set up your environment to develop applications with commercetools using the TypeScript SDK.

This exercise walks you through a hands-on setup. For the full SDK reference, including all middleware options and multi-API support, see Get started with the TypeScript SDK.
TypeScript SDK v3 client: This learning path uses the v3 client, which is Promise-based. The v2 client was deprecated in October 2024 and no longer receives updates. All code examples in this module use v3 patterns. If working with existing code using v2, refer to the TypeScript SDK getting started guide for migration guidance.

To follow along, you'll need:

  • A text editor or preferred TypeScript IDE
  • The Node.js runtime to execute your program code

Pay special attention to version requirements.

Install text editor

Check Node.js runtime version

To check the current version of Node.js on your computer, run the following command in your terminal:

node -v

If the installed version of Node.js is lower than 18, you will need to switch to a newer version. The method you use to do this depends on the initial installation process of Node.js on your computer, whether through NVM, FNM, or another Node.js version manager.

If you don't have Node.js installed, we recommend using a Node.js version manager to install it. Version managers simplify installing and switching to different versions. The most popular solutions are NVM and FNM. We recommend NVM for this tutorial, as it has higher adoption and more supporting documentation for a large variety of use cases. Chose one of the solutions and follow the instructions to install them:

Install the SDK

Let's now install the SDK on your machine.

Step 1: Create local repository

Create a new empty folder for a local code repository to install the SDK, and open it in VS Code. We named ours commercetools-environment.
New empty folder called commercetools environment.
Now open VS Code and open the new folder: select File > Open Folder > {select your folder} > Open.
Next, open a terminal in VS Code: select Terminal > New Terminal. The terminal should automatically be pointing to the folder of your new repository. The terminal should display the name of the folder that you created. Make sure you are not located in a subfolder of your repository.
Terminal showing the new empty folder called commercetools environment.

Step 2: Initialize the project

Run the appropriate initialization command based on your chosen package manager:

Package managerInitialization command
npmnpm init -y
pnpmpnpm init -y
yarnyarn init -y

Step 3: Install SDK packages

Install the TypeScript SDK packages listed in the Install the TypeScript SDK section of the SDK documentation:
Package managerCommand
npmnpm install @commercetools/ts-client @commercetools/platform-sdk
pnpmpnpm install @commercetools/ts-client @commercetools/platform-sdk
yarnyarn add @commercetools/ts-client @commercetools/platform-sdk
In addition to the SDK packages, install node-fetch and dotenv for this exercise:
Package managerCommand
npmnpm install node-fetch dotenv
pnpmpnpm install node-fetch dotenv
yarnyarn add node-fetch dotenv

Step 4: Finish setup

Once we have all of the packages installed, package.json should display four dependencies. To check this, open Explorer within VS Code (Mac Shortcut ⇧⌘E and Windows Shortcut Ctrl+K R) and inspect the files within the project. You should see a new file called package.json.
Package.json showing all four packages installed.

Do you see all the packages installed? Great, you are ready to create a commercetools application!

Test your setup

Let's now check if the SDK is set up correctly or not. Make sure that you have created an API Client as we mentioned previously before continuing.

Step 5: Set up an API Client in your SDK

For the TypeScript SDK, create a file apiClient.js and place it in a folder called /impl. The following sections walk through each part of the file.
This client uses a subset of available middleware. For all middleware types and configuration options, see the TypeScript SDK middleware reference.

Imports and configuration

Start with the required imports and environment variable configuration. These values come from the API Client you created in the Merchant Center.

import fetch from 'node-fetch';
import { createApiBuilderFromCtpClient } from '@commercetools/platform-sdk';
import { ClientBuilder } from '@commercetools/ts-client';
import 'dotenv/config';

// --- Configuration ---
const projectKey = process.env.CTP_PROJECT_KEY;
const clientId = process.env.CTP_CLIENT_ID;
const clientSecret = process.env.CTP_CLIENT_SECRET;
const authUrl = process.env.CTP_AUTH_URL;
const apiUrl = process.env.CTP_API_URL;
const scopes = [`manage_customers:${projectKey}`];

Authentication and HTTP middleware

Every client needs two core middleware components: one for authentication (obtaining and refreshing OAuth tokens) and one for making HTTP requests.

// Auth Middleware Options
const authMiddlewareOptions = {
  host: authUrl,
  projectKey: projectKey,
  credentials: { clientId, clientSecret },
  scopes: scopes,
  httpClient: fetch,
};

// Http Middleware Options
const httpMiddlewareOptions = {
  host: apiUrl,
  includeResponseHeaders: true,
  maskSensitiveHeaderData: false,
  includeOriginalRequest: true,
  includeRequestInErrorResponse: true,
  enableRetry: true,
  retryConfig: {
    maxRetries: 3,
    retryDelay: 200,
    backoff: false,
    retryCodes: [500, 503],
  },
  httpClient: fetch,
};
The retryConfig inside httpMiddlewareOptions automatically retries requests that fail with 500 or 503 status codes, up to 3 times.

Custom middleware

You can add custom middleware to modify requests (for example, adding headers) or to control logging output. These are optional but useful in practice.

// Function for custom header middleware
function createCustomHeaderMiddleware() {
  return (next) => (request) => {
    return next({
      ...request,
      headers: {
        ...request.headers,
        'accept-language': 'en-AU',
      },
    });
  };
}

// Custom logger middleware configuration
const customLoggerMiddleware = {
  logLevel: 'debug',
  httpMethods: ['POST', 'GET'],
  maskSensitiveData: true,
  logger: (method, ...args) => {
    console.log(`[CUSTOM LOGGER] ${method}`, ...args);
  },
};

Resilience middleware

Two additional middleware components help your application handle real-world conditions:

  • Correlation ID middleware: attaches a unique ID to each request for tracing and debugging.
  • Concurrent modification middleware: automatically retries requests that fail with a 409 Conflict error by using the updated resource version.
// Correlation ID Middleware Options
const correlationIdMiddlewareOptions = {
  // Replace with your own UUID, ULID, or a generator function. Do not use this example in production!
  generate: () => 'cd260fc9-c575-4ba3-8789-cc4c9980ee4e',
};

// Concurrent Modification Middleware Options
const concurrentModificationMiddlewareOptions = {
  concurrentModificationHandlerFn: (version, request) => {
    console.log(`Concurrent modification error, retry with version ${version}`);
    request.body.version = version;
    return JSON.stringify(request.body);
  },
};

Build and export the client

Finally, chain all the middleware together using ClientBuilder and create the API root object.
// --- Client Creation ---
const client = new ClientBuilder()
  .withProjectKey(projectKey)
  .withClientCredentialsFlow(authMiddlewareOptions)
  .withLoggerMiddleware(customLoggerMiddleware)
  .withCorrelationIdMiddleware(correlationIdMiddlewareOptions)
  .withMiddleware(createCustomHeaderMiddleware())
  .withHttpMiddleware(httpMiddlewareOptions)
  .withConcurrentModificationMiddleware(concurrentModificationMiddlewareOptions)
  // .withTelemetryMiddleware() // Optional: see TypeScript SDK middleware reference
  .build();

// --- API Root Creation ---
const apiRoot = createApiBuilderFromCtpClient(client).withProjectKey({
  projectKey,
});

export { apiRoot };
Create a file in the root directory called .env. Inside the file paste the environment variables from the API Client. Now our apiClient.js can read the secrets from this environment variables file.
Merchant Center new API client screen with manage customers scope selected.

Step 6: Fetch the Customer data

Now let's use our API Client to make the first call to the commercetools API. We can use a temporary file and discuss a proper project structure separately.

Create a file called customerFetch.js in the root folder. Copy the following code snippet and make sure to update the Customer ID.
import { apiRoot } from '../impl/apiClient.js'; // Update to map to your Import API root

const customerId = 'ded97f0d-a0bc-4478-b0f5-cf04932cf65c';

async function customerFetchById(customerId) {
  try {
    const response = await apiRoot
      .customers()
      .withId({
        ID: customerId,
      })
      .get()
      .execute();

    console.log('Success', JSON.stringify(response.body, null, 2));
  } catch (error) {
    console.log(JSON.stringify(error, null, 2));
  }
}

customerFetchById(customerId);

Step 7: Execute the code

Now it is time to execute the code by running the following command in the terminal:

node customerFetch.js

Ta-da! We have fetched the customer!

Customer successfully fetched.