The following instructions help you set up your environment to develop applications with commercetools 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
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
commercetools-environment.
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
| 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 |
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
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.
Do you see all the packages installed? Great, you are ready to create a commercetools application!
Test your setup
Step 5: Set up an API Client in your SDK
apiClient.js and place it in a folder called /impl. The following sections walk through each part of the file.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,
};
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 Conflicterror 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
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 };
.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 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.
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!