Set up the TypeScript SDK
Learn how to configure your environment for the TypeScript SDK.
After completing this module, you should be able to:
- Use the TypeScript SDK to work on a Composable Commerce Project.
The following instructions help you set up your environment to develop applications with Composable Commerce using the TypeScript SDK.
To follow along, you'll need:
- A text editor or preferred TypeScript IDE
- The Node.js runtime to execute your program code
Please pay special attention to version requirements.
Install text editor
In this tutorial, we use Visual Studio Code(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 or use your preferred package manager.
Check Node.js runtime version
Next, we need to ensure that we have the Node.js runtime installed. The SDK supports Node.js v12.22.7 (or later). Node.js versions 18 and 20 work for this tutorial.
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
.
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.
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: Run install command
We now want to install the SDK by running the install command in the terminal. This command differs based on the package manager that you use. By default Node.js comes with npm, alternatively, you can use Yarn or pnpm. If you want to use either of the latter two package managers, you must install them first. If you are unsure, use npm because it comes installed with Node.js.
In this tutorial, we are working with the Composable Commerce SDK Client package. Use the command that corresponds to your package manager.
Package manager | SDK Client |
---|---|
npm | npm install @commercetools/ts-client @commercetools/platform-sdk node-fetch dotenv |
pnpm | pnpm install @commercetools/ts-client @commercetools/platform-sdk node-fetch dotenv |
yarn | yarn add @commercetools/ts-client @commercetools/platform-sdk node-fetch dotenv |
Step 4: Finish setup
Once we have all of the packages installed, package.json
should display three 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
.
Do you see all the packages installed? Great, you are ready to create a Composable Commerce 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 4: Set up an API Client in your SDK
For the TypeScript SDK, use the following code example to create a file apiClient.js
and place it in a folder called /impl
.
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}`];// --- Middleware Functions ---// Function for custom header middlewarefunction createCustomHeaderMiddleware() {return (next) => (request) => {return next({...request,headers: {...request.headers,'accept-language': 'en-AU',},});};}// Function for custom logger middlewareconst customLoggerMiddleware = {logLevel: 'debug',httpMethods: ['POST', 'GET'],maskSensitiveData: true,logger: (method, ...args) => {console.log(`[CUSTOM LOGGER] ${method}`, ...args);},};// --- Middleware Options ---// Auth Middleware Optionsconst authMiddlewareOptions = {host: authUrl,projectKey: projectKey,credentials: { clientId, clientSecret },scopes: scopes,httpClient: fetch,};// Http Middleware Optionsconst 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,};// Correlation ID Middleware Optionsconst 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 Optionsconst concurrentModificationMiddlewareOptions = {concurrentModificationHandlerFn: (version, request) => {console.log(`Concurrent modification error, retry with version ${version}`);request.body.version = version;return JSON.stringify(request.body);},};// --- Optional Telemetry Middleware (Commented Out) ---/*const telemetryOptions = {createTelemetryMiddleware,apm: () => typeof require('newrelic'),tracer: () => typeof require('/absolute-path-to-a-tracer-module'),};*/// --- Client Creation ---const client = new ClientBuilder().withProjectKey(projectKey).withClientCredentialsFlow(authMiddlewareOptions).withLoggerMiddleware(customLoggerMiddleware).withCorrelationIdMiddleware(correlationIdMiddlewareOptions).withMiddleware(createCustomHeaderMiddleware()).withHttpMiddleware(httpMiddlewareOptions).withConcurrentModificationMiddleware(concurrentModificationMiddlewareOptions)// .withTelemetryMiddleware(telemetryOptions).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.
Step 5: Fetch the Customer data
Now let's use our API Client to make the first call to the Composable Commerce 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 rootconst 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 6: 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!
This self-learning module has taken you through the basics of setting up the SDK. You can find additional information on this process in our Get started with the TypeScript SDK page in the docs.
To get the most from the TypeScript SDK, follow the TypeScript SDK best practices guide.