# Set up the TypeScript SDK 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](/learning-developer-essentials/dev-tooling/ts-sdk-getting-started.md). **TypeScript SDK v3 client:** This learning path uses the v3 client, which is Promise-based. The v2 client was [deprecated in October 2024](/api/releases/2024-10-30-typescript-sdk-v2-client-is-now-deprecated) 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](/learning-developer-essentials/dev-tooling/ts-sdk-getting-started.md) 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 In this tutorial, we use [Visual Studio Code](https://code.visualstudio.com/)(VS Code), however, you can use any text editor that you are familiar with. In case you don’t have VS Code installed, you can follow the instructions [here](https://code.visualstudio.com/Download) or use your preferred package manager. ### Check Node.js runtime version Next, we need to ensure that we have the [Node.js](https://nodejs.org/en) runtime installed. The [SDK requires Node.js v18.17.x or later](/learning-developer-essentials/dev-tooling/ts-sdk-getting-started.md#requirements). To check the current version of Node.js on your computer, run the following command in your terminal: ```bash 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: - [NVM](https://github.com/nvm-sh/nvm#installing-and-updating) - [FNM](https://github.com/Schniz/fnm#installation) ## 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.](https://docs.commercetools.com/learning-developer-essentialsimages/prepare-your-work-environment/commercetools-enviroment-folder.png) 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.](https://docs.commercetools.com/learning-developer-essentialsimages/prepare-your-work-environment/javascript-terminal.png) ### Step 2: Initialize the project Run the appropriate initialization command based on your chosen package manager: | Package manager | Initialization command | | --- | --- | | npm | `npm init -y` | | pnpm | `pnpm init -y` | | yarn | `yarn init -y` | ### Step 3: Install SDK packages Install the TypeScript SDK packages listed in the [Install the TypeScript SDK](/learning-developer-essentials/dev-tooling/ts-sdk-getting-started.md#install-the-typescript-sdk) section of the SDK documentation: | Package manager | Command | | --- | --- | | npm | `npm install @commercetools/ts-client @commercetools/platform-sdk` | | pnpm | `pnpm install @commercetools/ts-client @commercetools/platform-sdk` | | yarn | `yarn add @commercetools/ts-client @commercetools/platform-sdk` | In addition to the SDK packages, install `node-fetch` and `dotenv` for this exercise: | Package manager | Command | | --- | --- | | npm | `npm install node-fetch dotenv` | | pnpm | `pnpm install node-fetch dotenv` | | yarn | `yarn 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.](https://docs.commercetools.com/learning-developer-essentialsimages/prepare-your-work-environment/packageJson3.png) 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](/learning-developer-essentials/prepare-your-work-environment/sdk-setup-process.md#create-an-api-client-in-the-merchant-center) 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](/learning-developer-essentials/dev-tooling/ts-sdk-middleware.md). #### 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. ```typescript 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. ```typescript // 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, timeout: 10000, enableRetry: true, retryConfig: { maxRetries: 3, retryDelay: 200, backoff: true, maxDelay: 5000, retryOnAbort: true, retryCodes: [500, 502, 504], }, httpClient: fetch, }; ``` The `retryConfig` inside `httpMiddlewareOptions` retries transient `5xx` responses and timed-out or aborted requests, up to 3 times, using exponential backoff. Setting a `timeout` together with `retryOnAbort` lets the SDK abort and retry stalled connections. #### 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. ```typescript // 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. ```typescript // 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. ```typescript // --- 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.](https://docs.commercetools.com/learning-developer-essentialsimages/prepare-your-work-environment/javascript-client-js-2.png) ### 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. ```typescript 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: ```bash node customerFetch.js ``` Ta-da! We have fetched the customer! ![Customer successfully fetched.](https://docs.commercetools.com/learning-developer-essentialsimages/prepare-your-work-environment/javascript-ran-code.png) To get the most from the TypeScript SDK, follow the [TypeScript SDK best practices](https://github.com/commercetools/commercetools-sdk-typescript/blob/master/BEST_PRACTICES.md) guide. ## Related pages - [Area overview page with navigation](/learning-developer-essentials.md) - [Previous page: SDK setup process](/learning-developer-essentials/prepare-your-work-environment/sdk-setup-process.md) - [Next page: Set up the Java SDK](/learning-developer-essentials/prepare-your-work-environment/set-up-the-java-sdk.md)