Skip to content

Node.js SDK

Overview

The Sinch Node.js SDK was designed for developers. The SDK components are built with the specific language first and foremost in mind. After that, our focus was to keep the design simple for users that only want to leverage specific API calls they use but ensure customizability and future-proof access to other parts of our infrastructure.

The Node.js SDK has added common capabilities to further streamline the interaction with our platform:

  • We have provided a simple HTTP component for ease of use.
  • We have provided automated token management/refresh code, so developers can use the system without micromanaging their authorization/authentication.
  • We have provided webhook helpers to serialize/deserialize in communication with our servers and validate webhook authentication.

Another goal of ours while designing this new Node.js SDK was to mimic our REST APIs as much as possible, while still providing a Node.js developer experience. We also use IDE type hints which, along with the REST API specification, allows the user to perform most API interactions without the need to use reference documentation. With all these common items, we hope to build out consistent frameworks with functionality all users will commonly leverage.

Discoverability is one of the key components of great DX, hence Node.js SDK namespaces are small and specific yet descriptive.

For example:

const response = await sinchClient.numbers.availableNumber.list({
  regionCode: 'US',
  type: 'LOCAL',
  capabilities: ['SMS', 'VOICE'],
});

The main client class organizes the Sinch product portfolio (called domains within SDK) and its features into hierarchy that produces an API that is easy to read and discover.

Node SDK example screenshot

The SDK runs on Node.js 18 and later. Node.js 18 and 20 have reached end of life, so we recommend using Node.js 22. Support for a Node.js version ends when it reaches end of life.

One 3rd party library is used by the Node.js SDK, the node-fetch package, until it can be removed when the oldest version to support will be Node.js 21 which supports the Fetch API natively.

The Sinch Node.js SDK allows you to quickly interact with the suite of APIs from inside your Node.js applications. When using the Node.js SDK, the code representing requests and queries sent to and responses received from the suite of APIs are structured similarly to those that are sent and received using the suite of APIs.

Installation

You can install the Sinch Node.js SDK using either NPM or Yarn:

npm install @sinch/sdk-core

Client

When using the Sinch Node.js SDK, you initialize communication with the Sinch backend by initializing the Node.js SDK's main client class. This client allows you to access the functionality of the Sinch Node.js SDK.

Initialization

Initialization of the Node.js SDK client can be done in two ways, depending on which product you are using.

Unified Project Authentication

Before initializing a client using this SDK, you'll need three pieces of information:

  • Your Project ID
  • An access key ID
  • An access key Secret

These values can be found on the Access Keys page of the Sinch Build Dashboard. You can also create new access key IDs and Secrets, if required.

Note

If you have trouble accessing the above link, ensure that you have gained access to the Conversation API by accepting the corresponding terms and conditions.

To start using the SDK, you need to initialize the main client class with your credentials from your Sinch dashboard.

const {SinchClient} = require('@sinch/sdk-core');

const sinchClient = new SinchClient({
    projectId: "YOUR_project_id",
    keyId: "YOUR_access_key",
    keySecret: "YOUR_access_secret"
});
Note

For testing purposes on your local environment it's fine to use hardcoded values, but before deploying to production we strongly recommend using environment variables to store the credentials, as in the following example:

.env File

PROJECTID="YOUR_project_id"
ACCESSKEY="YOUR_access_key"
ACCESSSECRET="YOUR_access_secret" 

app.js File

const {SinchClient} = require('@sinch/sdk-core');

const sinchClient = new SinchClient({
    projectId: process.env.PROJECTID,
    keyId: process.env.ACCESSKEY,
    keySecret: process.env.ACCESSSECRET
});
Note

If you are using the Node.js SDK for multiple products that use different sets of authentication credentials, you can include all of the relevant credentials in the same configuration object, as in the following example:

const {SinchClient} = require('@sinch/sdk-core');

const sinchClient = new SinchClient({
    projectId: "YOUR_project_id",
    keyId: "YOUR_access_key",
    keySecret: "YOUR_access_secret",
    applicationKey: "YOUR_application_key",
    applicationSecret: "YOUR_application_secret"
});

Application Authentication

To start using the SDK, you need to initialize the main client class with your credentials from your Sinch dashboard.

const {SinchClient} = require('@sinch/sdk-core');

const sinchClient = new SinchClient({
    applicationKey: "YOUR_application_key",
    applicationSecret: "YOUR_application_secret"
});
Note

For testing purposes on your local environment it's fine to use hardcoded values, but before deploying to production we strongly recommend using environment variables to store the credentials, as in the following example:

.env File

APPKEY="YOUR_application_key"
APPSECRET="YOUR_application_secret" 

app.js File

const {SinchClient} = require('@sinch/sdk-core');

const sinchClient = new SinchClient({
    applicationKey: process.env.APPKEY,
    applicationSecret: process.env.APPSECRET
});
Note

If you are using the Node.js SDK for multiple products that use different sets of authentication credentials, you can include all of the relevant credentials in the same configuration object, as in the following example:

const {SinchClient} = require('@sinch/sdk-core');

const sinchClient = new SinchClient({
    projectId: "YOUR_project_id",
    keyId: "YOUR_access_key",
    keySecret: "YOUR_access_secret",
    applicationKey: "YOUR_application_key",
    applicationSecret: "YOUR_application_secret"
});

Domains

The Node.js SDK currently supports the following products:

Numbers Domain

Note:

This guide describes the syntactical structure of the Node.js SDK for the Numbers API, including any differences that may exist between the API itself and the SDK. For a full reference on Numbers API calls and responses, see the Numbers API Reference.

The code sample below is an example of how to use the Node.js SDK to list the available numbers given a set of constraints. We've also provided an example that accomplishes the same task using the REST API.

snippet.js
/**
 * Class to list some Sinch Virtual Numbers through the Conversation API using the Sinch Node.js SDK.
 */
export class NumbersSample {
  /**
   * @param { import('@sinch/sdk-core').NumbersService } numbersService - the NumbersService instance from the Sinch SDK containing the API methods.
   */
  constructor(numbersService) {
    this.numbersService = numbersService;
  }

  async start() {

    const response = await this.numbersService.searchForAvailableNumbers({
      regionCode: 'US',
      type: 'LOCAL',
    });

    console.log('Response:', response.availableNumbers);
  }
}

This example highlights the following required to successfully make a Numbers API call using the Sinch Node.js SDK:

The Sinch Node.js SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, sinch.numbers.[endpoint_category].[method()].

Endpoint categories

In the Sinch Node.js SDK, Numbers API endpoints are accessible through the client. The naming convention of the endpoint's representation in the SDK matches the API:

For example:

var numbers = await sinchClient.numbers.availableNumber.list({
    regionCode: 'US',
    type: 'LOCAL'
});

numbers.availableNumber endpoint category

The numbers.availableNumber category of the Node.js SDK corresponds to the availableNumbers endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

numbers.activeNumber endpoint category

The numbers.activeNumber category of the Node.js SDK corresponds to the activeNumbers endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

numbers.availableRegions endpoint category

The numbers.availableRegions category of the Node.js SDK corresponds to the availableRegions endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

API operationSDK method
List available regionslist()

numbers.callbackConfiguration endpoint category

The numbers.callbackConfiguration category of the Node.js SDK corresponds to the callbackConfiguration endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

Request and query parameters

Requests and queries made using the Node.js SDK are similar to those made using the Numbers API. Path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding Node.js method.

For example, consider this example in which the get() method of the numbers.activeNumber class is invoked:


var numResponse = sinchClient.numbers.activeNumber.get({
  phoneNumber: "PHONE_NUMBER"
  });

url = "https://numbers.api.sinch.com/v1/projects/" + projectId + "/activeNumbers/" + phoneNumber

When using the Numbers API, projectId and phoneNumber would be included as path parameters in the request. With the Node.js SDK, the phoneNumber parameter is included as an argument in the get() method.

Responses

Response fields match the API responses. They are delivered as JavaScript objects.

Conversation Domain

Note:

This guide describes the syntactical structure of the Node.js SDK for the Conversation API, including any differences that may exist between the API itself and the SDK. For a full reference on Conversation API calls and responses, see the Conversation REST API Reference.

The code sample below is an example of how to use the Node.js SDK to send an SMS text message. We've also provided an example that accomplishes the same task using the REST API (note that this REST API example would be included in an mjs instead of a js file, and it uses Basic Authentication instead of OAuth2).

send-message.js
const { SinchClient } = require('@sinch/sdk-core');

const sinchClient = new SinchClient({
    projectId: "YOUR_project_id",
    keyId: "YOUR_access_key",
    keySecret: "YOUR_access_secret"
});

async function run(){
    const response = await sinchClient.conversation.messages.send({
        sendMessageRequestBody: {
            app_id: "YOUR_app_ID",
            recipient: {
                identified_by: {
                    channel_identities: [
                        {
                            channel: "SMS",
                            identity: "RECIPIENT_number"
                        }
                    ]
                }
            },
            message: {
                text_message: {
                    text: "This is a test message using the Sinch Node.js SDK"
                }
            },
            channel_properties: {
                SMS_SENDER: "YOUR_sms_sender"
            }
        }
    });

    console.log(JSON.stringify(response));
}
run();

The Sinch Node.js SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, sinch.conversation.[endpoint_category].[method()].

Endpoint categories

In the Sinch Node.js SDK, Conversation API endpoints are accessible through the client (either a general client or a Conversation-specific client). The naming convention of the endpoint's representation in the SDK matches the API:

For example:

const response = await sinchClient.conversation.messages.send({
    sendMessageRequestBody: {
        app_id: "YOUR_app_ID",
        recipient: {
            identified_by: {
                channel_identities: [
                    {
                        channel: "SMS",
                        identity: "RECIPIENT_number"
                    }
                ]
            }
        },
        message: {
            text_message: {
                text: "This is a test message using the Sinch Node.js SDK"
            }
        },
        channel_properties: {
            SMS_SENDER: "YOUR_sms_sender"
        }
    }
});

messages endpoint category

The messages category of the Node.js SDK corresponds to the messages endpoint. The mapping between the API operations and corresponding methods are described below:

API operationSDK method
Send a messagesend, or you could use any of the following message-specific methods:
sendCardMessage
sendCarouselMessage
sendChoiceMessage
sendContactInfoMessage
sendListMessage
sendLocationMessage
sendMediaMessage
sendTemplateMessage
sendTextMessage
Get a messageget
Delete a messagedelete
List messageslist
Update a message's metadataupdate

app endpoint category

The app category of the Node.js SDK corresponds to the apps endpoint. The mapping between the API operations and corresponding methods are described below:

contact endpoint category

The contact category of the Node.js SDK corresponds to the contacts endpoint. The mapping between the API operations and corresponding methods are described below:

API operationSDK method
List contactslist
Create a contactcreate
Get a contactget
Delete a contactdelete
Update a contactupdate
Merge two contactsmergeContact
Get channel profilegetChannelProfile

conversation endpoint category

The conversation category of the Node.js SDK corresponds to the conversations endpoint. The mapping between the API operations and corresponding methods are described below:

events endpoint category

The events category of the Node.js SDK corresponds to the events endpoint. The mapping between the API operations and corresponding methods are described below:

API operationSDK method
Send an eventsend, or you could use any of the following message-specific methods: sendComposingEvent, sendComposingEndEvent, sendCommentReplyEvent, sendAgentJoinedEvent, sendAgentLeftEvent, or sendGenericEvent

transcoding endpoint category

The transcoding category of the Node.js SDK corresponds to the messages:transcode endpoint. The mapping between the API operations and corresponding methods are described below:

API operationSDK method
Transcode a messagetranscodeMessage

capability endpoint category

The capability category of the Node.js SDK corresponds to the capability endpoint. The mapping between the API operations and corresponding methods are described below:

API operationSDK method
Capability lookuplookup

webhooks endpoint category

The webhooks category of the Node.js SDK corresponds to the webhooks endpoint. The mapping between the API operations and corresponding methods are described below:

templatesV2 endpoint category

The templatesV2 category of the Node.js SDK corresponds to the Templates-V2 endpoint. The mapping between the API operations and corresponding methods are described below:

Request and query parameters

Requests and queries made using the Node.js SDK are similar to those made using the Conversation API. Many of the fields are named and structured similarly. Additionally, path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding Node.js method.

app_id: "{APP_ID}"

Note that the fields have the same name. Additionally, path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding method. For example, consider this example in which the get method of the message class is invoked:


const response = await sinchClient.conversation.messages.get({
                    message_id:"YOUR_message_id"
                    messages_source:"CONVERSATION_SOURCE"
                    });

When using the Conversation API, message_id would be included as a path parameter, and messages_source would be included as a query parameter in the JSON payload. With the Node.js SDK, both parameters are included as arguments in the get method.

Responses

Response fields match the API responses. They are delivered as JavaScript objects.

SMS Domain (existing integrations only)

End of sale: standalone SMS REST API

The SMS domain calls the standalone SMS REST API, which reached end of sale on 15 April 2026 and is no longer available to new customers. All new SMS integrations must use the Conversation domain with the SMS channel of Conversation API. Use the SMS domain only to maintain an existing integration.

Show the SMS domain reference (standalone SMS REST API, existing integrations only)
Note:

This guide describes the syntactical structure of the Node.js SDK for the standalone SMS REST API (existing integrations only), including any differences that may exist between the API itself and the SDK. For a full reference on SMS API calls and responses, see the standalone SMS REST API Reference.

For existing standalone SMS REST API integrations, the code sample below shows how to send a message with the Node.js SDK. For new integrations, send SMS with the Conversation domain instead. We've also provided an example that accomplishes the same task using the REST API.

send-message.js
// Standalone SMS REST API: existing integrations only (end of sale 15 April 2026). For new integrations, use the SMS channel of Conversation API: https://developers.sinch.com/docs/conversation/channel-support/sms/
/**
 * Sinch Node.js Snippet
 * See: https://github.com/sinch/sinch-sdk-node/examples/snippets
 */
import { SinchClient } from '@sinch/sdk-core';
import * as dotenv from 'dotenv';
dotenv.config();

async function main() {
  const projectId = process.env.SINCH_PROJECT_ID ?? 'MY_PROJECT_ID';
  const keyId = process.env.SINCH_KEY_ID ?? 'MY_KEY_ID';
  const keySecret = process.env.SINCH_KEY_SECRET ?? 'MY_KEY_SECRET';
  const smsRegion = process.env.SINCH_SMS_REGION ?? 'MY_SMS_REGION';

  // The sender phone number (Sinch virtual number, alphanumeric sender ID, or short code)
  const senderNumber = 'SENDER_NUMBER';
  // The recipient phone number, in E.164 format (e.g., +46701234567)
  const recipientPhoneNumber = 'RECIPIENT_PHONE_NUMBER';
  // The body of the SMS message
  const body = 'A body text here';

  const sinch = new SinchClient({ projectId, keyId, keySecret, smsRegion });

  try {
    const response = await sinch.sms.batches.send({
      sendSMSRequestBody: {
        from: senderNumber,
        to: [recipientPhoneNumber],
        body,
      },
    });
    console.log('✅ Successfully sent the SMS batch.');
    console.log(`Response:\n${JSON.stringify(response, null, 2)}`);
  } catch (err) {
    console.error('❌ Failed to send the SMS batch:');
    console.error(err);
  }
}

main();

The Sinch Node.js SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, sinch.sms.[endpoint_category].[method()].

Endpoint categories

In the Sinch Node.js SDK, SMS API endpoints are accessible through the client. The naming convention of the endpoint's representation in the SDK matches the API:

For example:

const response = await sinchClient.sms.batches.send({
    sendSMSRequestBody: {
        to: [
            "+13215013855"
        ],
        from: "+12074193397",
        body: "This is a test message from the Node.js SDK."
    }
});

sms.batches endpoint category

The sms.batches category of the Node.js SDK corresponds to the batches endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

API operationSDK method
Sendsend()
List batcheslist()
Dry rundryRun()
Get a batch messageget()
Update a batch messageupdate()
Replace a batchreplace()
Cancel a batch messagecancel()
Send delivery feedback for a messagesendDeliveryFeedback()

sms.deliveryReports endpoint category

The sms.deliveryReports category of the Node.js SDK corresponds to the delivery_report and delivery_reports endpoints. The mapping between the API operations and corresponding Node.js methods are described below:

sms.groups endpoint category

The sms.groups category of the Node.js SDK corresponds to the groups endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

API operationSDK method
List groupslist()
Create a groupcreate()
Retrieve a groupget()
Update a groupupdate()
Replace a groupreplace()
Delete a groupdelete()
List group member phone numberslistMembers()

sms.inbounds endpoint category

The sms.inbounds category of the Node.js SDK corresponds to the inbounds endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

API operationSDK method
List incoming messageslist()
Retrieve inbound messageget()

Request and query parameters

Requests and queries made using the Node.js SDK are similar to those made using the SMS API. Additionally, path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding Node.js method.

For example, consider this example in which the get() method of the sms.batches class is invoked:

const smsResponse = sinchClient.sms.batches.get({
  batch_id: "BATCH_ID"
  });

When using the SMS API, service_plan_id and batch_id would be included as path parameters in the JSON payload. With the Node.js SDK, the batch_id parameter is included as an argument in the get() method.

Note:

Note that the service_plan_id path parameter does not need to be included in any requests created by the Node.js SDK.

Responses

Response fields match the API responses. They are delivered as JavaScript objects.

Voice Domain

Note:

This guide describes the syntactical structure of the Node.js SDK for the Voice API, including any differences that may exist between the API itself and the SDK. For a full reference on Voice API calls and responses, see the Voice API Reference.

The code sample below is an example of how to use the Node.js SDK to make a Text to speech phone call. We've also provided an example that accomplishes the same task using the REST API.

index.js
/**
 * Class to place a demo Voice call using the Sinch Node.js SDK.
 */
export class VoiceSample {
  /**
   * @param { import('@sinch/sdk-core').VoiceService } voiceService - the VoiceService instance from the Sinch SDK containing the API methods.
   */
  constructor(voiceService) {
    this.voiceService = voiceService;
  }

  async start() {
    const caller = 'CALLER_NUMBER';
    const recipient = 'RECIPIENT_PHONE_NUMBER';

    const response = await this.voiceService.callouts.tts({
      ttsCalloutRequestBody: {
        method: 'ttsCallout',
        ttsCallout: {
          destination: {
            type: 'number',
            endpoint: recipient,
          },
          cli: caller,
          text: 'Hello, this is a call from Sinch. Congratulations! You just made your first call.',
        },
      },
    });

    console.log('Call ID:', response.callId);
  }
}

This example highlights the following required to successfully make a Voice API call using the Sinch Node.js SDK:

The Sinch Node.js SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, sinch.voice.[endpoint_category].[method()].

Endpoint categories

In the Sinch Node.js SDK, Voice API endpoints are accessible through the client. The naming convention of the endpoint's representation in the SDK matches the API:

For example:

const response = await sinchClient.voice.callouts.tts({
        ttsCalloutRequestBody: {
           method: 'ttsCallout',
           ttsCallout: {
               cli: 'YOUR_Sinch_number',
               destination: {
                   type: 'number',
                   endpoint: 'YOUR_phone_number'
               },
               text: 'This is a test call from Sinch using the Node.js SDK.'
           }
        }
       });

voice.callouts endpoint category

The voice.callouts category of the Node.js SDK corresponds to the callouts endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

voice.calls endpoint category

The voice.calls category of the Node.js SDK corresponds to the calls endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

API operationSDK method
Get information about a callget()
Manage call with callLegmanageWithCallLeg()
Updates a call in progressupdate()

voice.conferences endpoint category

The voice.conferences category of the Node.js SDK corresponds to the conferences endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

voice.applications endpoint category

The voice.applications category of the Node.js SDK corresponds to the configuration endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

Call events and SVAML

The Voice API uses call events and SVAML responses to dynamically control calls throughout their life cycle. The Node.js SDK has a number of builder and helper methods designed to aid in quickly constructing the correct SVAML responses for the various call events. The builder and helper methods available and their parameters are described in the example and tables below.

const iceResponse = new Voice.IceSvamletBuilder()
        .setAction(Voice.iceActionHelper.hangup())
        .addInstruction(Voice.iceInstructionHelper.say('Thank you for calling Sinch! This call will now end.', 'en-US'))
        .build();
Call eventBuilder method nameMethods
Answered Call EventAceSvamletBuilder()setAction() or addInstruction()
Incoming Call EventIceSvamletBuilder()setAction() or addInstruction()
Prompt Input EventPieSvamletBuilder()setAction() or addInstruction()

Using these builder methods you can then build your SVAML responses using the following methods:

Actions:

Helper method nameAction
Voice.aceActionHelper.connectConfconnectConf
Voice.aceActionHelper.continuecontinue
Voice.aceActionHelper.hanguphangup
Voice.aceActionHelper.runMenurunMenu
Voice.iceActionHelper.connectConfconnectConf
Voice.iceActionHelper.connectMxpconnectMxp
Voice.iceActionHelper.connectPstnconnectPstn
Voice.iceActionHelper.connectSipconnectSip
Voice.iceActionHelper.hanguphangup
Voice.iceActionHelper.parkpark
Voice.iceActionHelper.runMenurunMenu
Voice.pieActionHelper.connectConfconnectConf
Voice.pieActionHelper.connectSipconnectSip
Voice.pieActionHelper.continuecontinue
Voice.pieActionHelper.hanguphangup
Voice.pieActionHelper.runMenurunMenu

Instructions:

Helper method nameAction
Voice.aceActionHelper.playFilesplayFiles
Voice.aceActionHelper.saysay
Voice.aceActionHelper.setCookiesetCookie
Voice.aceActionHelper.startRecordingstartRecording
Voice.iceActionHelper.answeranswer
Voice.iceActionHelper.playFilesplayFiles
Voice.iceActionHelper.saysay
Voice.iceActionHelper.sendDtmfsendDtmf
Voice.iceActionHelper.setCookiesetCookie
Voice.iceActionHelper.startRecordingstartRecording
Voice.pieActionHelper.playFilesplayFiles
Voice.pieActionHelper.saysay
Voice.pieActionHelper.sendDtmfsendDtmf
Voice.pieActionHelper.setCookiesetCookie
Voice.pieActionHelper.startRecordingstartRecording
Voice.pieActionHelper.stopRecordingstopRecording

Request and query parameters

Requests and queries made using the Node.js SDK are similar to those made using the Voice API. Path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding Node.js method.

For example, consider this example in which the get() method of the voice.calls class is invoked:

const response = await sinchClient.voice.calls.get({
        callId: 'YOUR_call_id'
    });

url = "https://calling.api.sinch.com/calling/v1/calls/id/" + callId

When using the Voice API, callId would be included as a path parameter in the request. With the Node.js SDK, the callId parameter is used in an object passed as an argument in the get() method.

Responses

Response fields match the API responses. They are delivered as Javascript objects.

Voice v2 Domain

Note:

This guide describes the syntactical structure of the Node.js SDK for the Voice API v2, including any differences that may exist between the API itself and the SDK. For a full reference on Voice API v2 calls and responses, see the Voice API v2 Reference.

The code sample below is an example of how to use the Node.js SDK to make a Text to speech phone call. We've also provided an example that accomplishes the same task using the REST API.

start.js
/**
 * Sinch Node.js Snippet
 * See: https://github.com/sinch/sinch-sdk-node/examples/snippets
 */
import { SinchClient, Voice } from '@sinch/sdk-core';
import * as dotenv from 'dotenv';
dotenv.config();

async function main() {
  const projectId = process.env.SINCH_PROJECT_ID ?? 'MY_PROJECT_ID';
  const keyId = process.env.SINCH_KEY_ID ?? 'MY_KEY_ID';
  const keySecret = process.env.SINCH_KEY_SECRET ?? 'MY_KEY_SECRET';

  // The phone number to be used as the caller ID, in E.164 format (e.g., +12025550123)
  const sinchPhoneNumber = process.env.SINCH_PHONE_NUMBER || 'MY_SINCH_PHONE_NUMBER';
  // The phone number you want to call, in E.164 format (e.g., +12025550123)
  const recipientPhoneNumber = 'RECIPIENT_PHONE_NUMBER';

  const sinch = new SinchClient({ projectId, keyId, keySecret });

  try {
    const response = await sinch.voice.v2.calls.start({
      createCallRequestBody: {
        commands: new Voice.v2.CommandsSequenceCreator()
          .dial((dialCreator) => {
            dialCreator
              .name('Node_SDK_Snippet_Call')
              .from(Voice.v2.Destination.of(sinchPhoneNumber))
              .to(Voice.v2.Destination.of(recipientPhoneNumber))
              .onAnswer((sequence) => {
                sequence.text('Hello, your call is now connected.', 'Emma', {
                  onFinish: Voice.v2.Calls.hangup(),
                });
              });
          })
          .build(),
      },
    });
    console.log(`✅ Successfully started a Voice v2 call to ${recipientPhoneNumber}.`);
    console.log(`Response:\n${JSON.stringify(response, null, 2)}`);
  } catch (err) {
    console.error(`❌ Failed to start a Voice v2 call to ${recipientPhoneNumber}:`);
    console.error(err);
  }
}

main();

This example highlights the following required to successfully make a Voice API call using the Sinch Node.js SDK:

The Sinch Node.js SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, sinch.voice.v2.[endpoint_category].[method()].

Endpoint categories

In the Sinch Node.js SDK, Voice API endpoints are accessible through the client. The naming convention of the endpoint's representation in the SDK matches the API:

For example:

const response = await sinch.voice.v2.calls.start({
      createCallRequestBody: {
        commands: new Voice.v2.CommandsSequenceCreator()
          .dial((dialCreator) => {
            dialCreator
              .name('Node_SDK_Snippet_Call')
              .from(Voice.v2.Destination.of(sinchPhoneNumber))
              .to(Voice.v2.Destination.of(recipientPhoneNumber))
              .onAnswer((sequence) => {
                sequence.text('Hello, your call is now connected.', 'Emma', {
                  onFinish: Voice.v2.Calls.hangup(),
                });
              });
          })
          .build()}})

Request and query parameters

Requests and queries made using the Node.js SDK are similar to those made using the Voice API. Path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding Node.js method.

For example, consider this example in which the get() method of the voice.v2.calls class is invoked:

const response = await sinch.voice.v2.calls.get({
      callId,
    });

url = "https://voice.api.sinch.com/v2/projects/${projectId}/calls/${callId}"

When using the Voice API, callId would be included as a path parameter in the request. With the Node.js SDK, the callId parameter is used in an object passed as an argument in the get() method.

Responses

Response fields match the API responses. They are delivered as Javascript objects.

Verification Domain

Note:

This guide describes the syntactical structure of the Node.js SDK for the Verification API, including any differences that may exist between the API itself and the SDK. For a full reference on Verification API calls and responses, see the Verification API Reference.

The code sample below is an example of how to use the Node.js SDK to initiate an Verification SMS PIN request. We've also provided an example that accomplishes the same task using the REST API.

verificationSample.js
import { Verification } from '@sinch/sdk-core';
import inquirer from 'inquirer';

/**
 * Class to handle a phone number verification using SMS.
 */
export class VerificationSample {
  /**
   * @param { import('@sinch/sdk-core').VerificationService } verificationService - the VerificationService instance from the Sinch SDK containing the API methods.
   */
  constructor(verificationService) {
    this.verificationService = verificationService;
  }

  /**
   * Starts the verification process by prompting the user for a phone number,
   * sending a verification request, asking for the verification code, and reporting it.
   * @return {Promise<void>}
   */
  async start() {
    // Step 1: Ask the phone number to verify
    const e164Number = await this.promptPhoneNumber();

    try {
      // Step 2: Start the phone number verification
      const verificationId = await this.startSmsVerification(this.verificationService.verifications, e164Number);

      // Step 3: Ask the user for the received verification code
      const code = await this.promptSmsCode();

      // Step 4: Report the verification code and complete the process
      await this.reportSmsVerification(this.verificationService.verifications, code, verificationId);

      console.log('Verification successfully completed.');
    } catch (error) {
      console.error('An error occurred during the verification process:', error);
    }
  }

  /**
   * Prompts the user to enter their phone number.
   * @return {Promise<string>} The phone number entered by the user.
   */
  async promptPhoneNumber() {
    const userInput = await inquirer.prompt([
      {
        type: 'input',
        name: 'phoneNumber',
        message: 'Enter the phone number you want to verify (E.164 format):',
        validate: (input) => input ? true : 'Phone number cannot be empty.',
      },
    ]);

    return userInput.phoneNumber;
  }

  /**
   * Sends a request to start SMS verification for a phone number.
   * @param {import('@sinch/sdk-core').VerificationsApi} verificationStarter - The VerificationsApi instance.
   * @param {string} phoneNumber - The phone number to verify.
   * @return {Promise<string>} The verification ID if the request is successful.
   */
  async startSmsVerification(verificationStarter, phoneNumber) {
    console.log(`Sending a verification request to ${phoneNumber}`);

    const requestData = Verification.startVerificationHelper.buildSmsRequest(phoneNumber);

    try {
      const response = await verificationStarter.startSms(requestData);

      if (!response.id) {
        throw new Error('Verification ID is undefined.');
      }

      console.log(`Verification started successfully. Verification ID: ${response.id}`);
      return response.id;
    } catch (error) {
      console.error('Failed to start SMS verification:', error);
      throw error;
    }
  }

  /**
   * Prompts the user to enter the verification code they received.
   * @return {Promise<string>} The verification code entered by the user.
   */
  async promptSmsCode() {
    const answers = await inquirer.prompt([
      {
        type: 'input',
        name: 'code',
        message: 'Enter the verification code you received:',
        validate: (input) => input ? true : 'Verification code cannot be empty.',
      },
    ]);
    return answers.code;
  }

  /**
   * Sends a request to report the verification code for a specific verification ID.
   * @param { import('@sinch/sdk-core').VerificationsApi } verificationReporter - The VerificationsApi instance.
   * @param {string} code - The verification code to report.
   * @param {string} id - The verification ID corresponding to the process.
   * @return {Promise<void>}
   */
  async reportSmsVerification(verificationReporter, code, id) {
    const requestData = Verification.reportVerificationByIdHelper.buildSmsRequest(id, code);

    try {
      const response = await verificationReporter.reportSmsById(requestData);
      console.log(`Verification reported successfully. Response status: ${response.status}`);
    } catch (error) {
      console.error('Failed to report SMS verification:', error);
      throw error;
    }
  }
}

This example highlights the following required to successfully make a Verification API call using the Sinch Node.js SDK:

The Sinch Node.js SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, sinch.verification.[endpoint_category].[method()].

Endpoint categories

In the Sinch Node.js SDK, Verification API endpoints are accessible through the client. The naming convention of the endpoint's representation in the SDK matches the API:

For example:

const startRequestData = verificationsHelper.buildStartSmsVerificationRequest(
                                                      "YOUR_phone_number");
const smsVerification = await sinchClient.verification.verifications.startSms(
                                                      startRequestData);

verification.verifications endpoint category

The verification.verifications category of the Node.js SDK corresponds to the verifications start endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

verification.verificationStatus endpoint category

The verification.verificationStatus category of the Node.js SDK corresponds to the verifications endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

Helper methods

The Node.js SDK has a number of helper methods designed to aid in quickly constructing the correct request bodies for the various methods. The helper methods available and their parameters are described in the example and table below.

const requestData = verificationHelper.buildStartSmsVerificationRequest(
                                          "YOUR_phone_number");
Request bodyHelper method nameParameters
Start SMS VerificationbuildStartSmsVerificationRequest()
  • phoneNumber
    *required
  • reference
Start FlashCall VerificationbuildStartFlashCallVerificationRequest()
  • phoneNumber
    *required
  • reference
  • dialTimeout
Start Callout VerificationbuildStartCalloutVerificationRequest()
  • phoneNumber
    *required
  • reference
Start Data VerificationbuildStartSeamlessVerificationRequest()
  • phoneNumber
    *required
  • reference
Report SMS Verification by IDbuildReportSmsVerificationByIdRequest()
  • id
    *required
  • code
    *required
  • cli
Report FlashCall Verification by IDbuildReportFlashCallVerificationByIdRequest()
  • id
    *required
  • cli
    *required
Report Phone Call Verification by IDbuildReportCalloutVerificationByIdRequest()
  • id
    *required
  • code
    *required
Report SMS Verification by IdentitybuildReportSmsVerificationByIdentityRequest()
  • identity
    *required
  • code
    *required
  • cli
Report FlashCall Verification by IdentitybuildReportFlashCallVerificationByIdentityRequest()
  • identity
    *required
  • cli
    *required
Report Phone Call Verification by IdentitybuildReportCalloutVerificationByIdentityRequest()
  • identity
    *required
  • code
    *required

Request and query parameters

Requests and queries made using the Node.js SDK are similar to those made using the Verification API. Path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding Node.js method.

For example, consider this example in which the getByIdentity() method of the verification.verificationStatus class is invoked:

const response = await sinchClient.verification.verificationStatus.getByIdentity({
    endpoint: 'PHONE_NUMBER',
    method: 'sms'
});

url = "https://verification.api.sinch.com/verification/v1/verifications/" + method + "/number/" + endpoint

When using the Verification API, method and endpoint would be included as path parameters in the request. With the Node.js SDK, the method and endpoint parameters are used in an object passed as an argument in the getByIdentity() method.

Responses

Response fields match the API responses. They are delivered as JavaScript objects.

Number Lookup Domain

Note:

This guide describes the syntactical structure of the Node.js SDK for the Number Lookup API, including any differences that may exist between the API itself and the SDK. For a full reference on Number Lookup API calls and responses, see the Number Lookup API Reference.

This code sample is an example of how to use the Node.js SDK to lookup a specified number. We've also provided an example that accomplishes the same task using the REST API.

NumberLookupSample.js
// This code looks up a specified number. 
/**
 * Class to lookup a number through the NumberLookup API using the Sinch Node.js SDK.
 */
export class NumberLookupSample {
  /**
   * @param { import('@sinch/sdk-core').NumberLookupService } numberLookupService - the NumberLookupService instance from the Sinch SDK containing the API methods.
   */
  constructor(numberLookupService) {
    this.numberLookupService = numberLookupService;
  }

  async start() {
    // The phone number to lookup in E.164 format
    const phoneNumber = 'PHONE_NUMBER_TO_LOOKUP';

    const response = await this.numberLookupService.lookup({
      numberLookupRequestBody: {
        number: phoneNumber,
      },
    });

    console.log('Response:', response);
  }
}

The Sinch Node.js SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, sinch.numberLookup().[method()].

Endpoint categories

In the Sinch Node.js SDK, Number Lookup API endpoints are accessible through the client:

For example:

const response = await sinch.numberLookup.lookup({
      numberLookupRequestBody: {
        number: phoneNumber,
        features: [ 'LineType' ],
      },
    });

Responses

Response fields match the API responses. They are delivered as JavaScript objects.

Fax Domain

Note:

This guide describes the syntactical structure of the Node.js SDK for the Fax API, including any differences that may exist between the API itself and the SDK. For a full reference on Fax API calls and responses, see the Fax API Reference.

The code sample below is an example of how to use the Node.js SDK to send a fax. We've also provided an example that accomplishes the same task using the REST API.

start.js
/**
 * Class to send a demo fax using the Sinch Node.js SDK.
 */
export class FaxSample {
  /**
   * @param { import('@sinch/sdk-core').FaxService } faxService - the FaxService instance from the Sinch SDK containing the API methods.
   */
  constructor(faxService) {
    this.faxService = faxService;
  }

  async start() {
    const recipient = 'YOUR_FAX_NUMBER';
    const contentUrl = 'https://developers.sinch.com/fax/fax.pdf';
    const callbackUrl = 'FAX_CALLBACK_URL';

    const response = await this.faxService.faxes.send({
      sendFaxRequestBody: {
        to: recipient,
        contentUrl,
        ...(callbackUrl !== 'FAX_CALLBACK_URL' && { callbackUrl }),
      },
    });

    const fax = response[0];
    console.log('Fax ID:', fax.id);
    console.log('Status:', fax.status);
    console.log('Response:', response);
  }
}

This example highlights the following required to successfully make a Fax API call using the Sinch Node.js SDK:

The Sinch Node.js SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, sinch.fax.[endpoint_category].[method()].

Endpoint categories

In the Sinch Node.js SDK, Fax API endpoints are accessible through the client. The naming convention of the endpoint's representation in the SDK matches the API:

For example:

const response = await fax.faxes.send({
      sendFaxRequestBody: {
        to: recipient,
        contentUrl,
        ...(callbackUrl !== 'FAX_CALLBACK_URL' && { callbackUrl }),
      },
});

Request and query parameters

Requests and queries made using the Node.js SDK are similar to those made using the Fax API. Path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding Node.js method.

For example, consider this example in which the get() method of the fax.faxes class is invoked:

const response = await sinch.fax.faxes.get({ id: faxId });

url = "https://fax.api.sinch.com/v3/projects/${projectId}/faxes/${faxId}"

When using the Fax API, faxId would be included as a path parameter in the request. With the Node.js SDK, the faxId parameter is used in an object passed as an argument in the get() method.

Responses

Response fields match the API responses. They are delivered as Javascript objects.

SDK features

Pagination objects

For operations that return multiple pages of objects, such as list operations, the API response that would normally be an array is instead wrapped inside an ApiPromiseList object. This object can take two forms, depending on how you have made the call:

PageResult

If you are using a traditional await in front of the method, the ApiPromiseList will take the form of a PageResult, as demonstrated by the following example:

const requestData: ListActiveNumbersRequestData = {
    regionCode: 'US',
    type: 'LOCAL',
    pageSize: 2,
  };

  // This call will return the data of the current page wrapped in a PageResult
  // We can then loop on the response while it has more pages
  let response: PageResult<ActiveNumber> = await sinchClient.numbers.activeNumber.list(requestData); 

  // The ActiveNumber are in the `data` property
  let activeNumbers: ActiveNumber[] = response.data;
  console.log(activeNumbers); // prints the content of a page

The array is contained in the data field and the object contains a hasNextPage boolean as well as a nextPage() function which can be used to iterate through the results.

// Loop on all the pages to get all the active numbers
  let reachedEndOfPages = false;
  while (!reachedEndOfPages) {
    if (response.hasNextPage) {
      response = await response.nextPage();
      activeNumbers = response.data;
      console.log(activeNumbers); // prints the content of a page
    } else {
      reachedEndOfPages = true;
    }
  }

Each call to the Sinch servers is visible in the code in the while loop.

AsyncIteratorIterable

If you using an iterator (for await (... of ...)), the ApiPromiseList will take the form of a AsyncIteratorIterable object which can be used to iterate through the results, as demonstrated by the following example:

const requestData: ListActiveNumbersRequestData = {
    regionCode: 'US',
    type: 'LOCAL',
    pageSize: 2,
  };

  for await (const activeNumber of sinchClient.numbers.activeNumber.list(requestData)) {
    console.log(activeNumber); // prints a single ActiveNumber
  }

With the iterator, the code is more concise but you have less control over the number of calls made to the API; the iterator will continue to make calls to the API to fetch the next page until the final page is returned.

Calling any Sinch API with the HTTP client

The Sinch Node.js SDK provides a low-level HTTP client, exposed as sinch.http, to call the endpoints that the SDK doesn't cover yet, or the APIs that have no SDK support at all.

When using the HTTP client, the SDK still handles:

  • the authentication, from the credentials of your SinchClient;
  • the retries of rate-limited (HTTP 429) responses;
  • the client settings, such as the timeout;
  • the User-Agent header.

The HTTP client is available from version 1.9.0.

When to use it

Use sinch.http when:

  • the endpoint you need isn't available in the SDK yet.
  • you want to try a new or beta API without waiting for an SDK release.

For endpoints already supported by the SDK, use their dedicated methods instead, such as sinch.numbers.list(), which validate your input and return typed models.

Getting started

The HTTP client uses the authentication configured in SinchClient, so you can initialize the Sinch client as usual.

import { SinchClient } from '@sinch/sdk-core';

const sinch = new SinchClient({
  projectId: 'YOUR_project_id',
  keyId: 'YOUR_access_key_id',
  keySecret: 'YOUR_access_key_secret',
});

Then call the method matching the HTTP verb, with the absolute URL of the endpoint:

const response = await sinch.http.get(
  'https://example.api.sinch.com/v1/resource',
  {
    queryParams: 'status=active&pageSize=5',
  },
);

console.log(response.status);
const resources = await response.content.asJson();

The URL and the query string are sent as you provide them. The URL is not validated, path segments are not encoded, and the only change to the query string is a leading ?, added when it is missing. A URLSearchParams value is encoded by URLSearchParams. A string is sent untouched.

The following methods are available. Every method is asynchronous and returns a Promise<HttpResponse>.

MethodDescription
get(url, params = {})Sends a GET request.
delete(url, params = {})Sends a DELETE request.
post(url, body?, params = {})Sends a POST request, with an optional body.
put(url, body?, params = {})Sends a PUT request, with an optional body.
patch(url, body?, params = {})Sends a PATCH request, with an optional body.
postFormData(url, form, params = {})Sends a POST request with a multipart/form-data body, to upload files.

params defaults to {}. It accepts the following fields:

FieldDescription
queryParamsThe query string, as a URLSearchParams or as an already URL-encoded string. The leading ? is optional.
headersThe request headers, as a record or as an HttpHeaders instance. Use an array of strings, or HttpHeaders.append, to repeat a header.
optionsRequest-level settings that override the client settings for this request only. See Request options.

Authentication

The authentication configured in the SinchClient is added by default to the requests of the HTTP client. When several credentials are configured, the SDK uses the first one available in this order.

  1. OAuth2, when keyId and keySecret are set. The access token is requested on the first call, cached and renewed when it expires. Any other credentials are ignored.
  2. The SMS API token, when apiToken is set.
  3. Application signing, when applicationKey and applicationSecret are set (Voice and Verification).

apiToken and the application credentials cannot both be set unless keyId and keySecret are also set, in which case OAuth2 is used. Since the project ID is part of the URL you build, it isn't required by the HTTP client.

To call an endpoint with a different authentication, disable the SDK authentication and set your own header:

const response = await sinch.http.get(
  'https://example.api.sinch.com/v1/resource',
  {
    headers: { Authorization: 'Bearer YOUR_token' },
    options: { useSinchAuth: false },
  },
);

useSinchAuth: false on the client disables authentication for every call and requires no credentials. A single call can turn authentication off. It cannot turn it back on when the client has it disabled.

Sending a request body

Serialize the body yourself and pass a string, a Buffer, or a Uint8Array. Set the content-type header yourself. Bytes are sent untouched, and a string is encoded with the charset of the content-type header (UTF-8 when there is none or it is unknown). The SDK throws if the header is missing.

const response = await sinch.http.post(
  'https://example.api.sinch.com/v1/resource',
  JSON.stringify({ name: 'My resource', status: 'active' }),
  {
    headers: { 'content-type': 'application/json' },
  },
);

To send a file as the whole body, read it with HttpHelpers.fromFile and pass the buffer to post, put, or patch:

import { HttpHelpers } from '@sinch/sdk-core';

const response = await sinch.http.put(
  'https://example.api.sinch.com/v1/files/report.pdf',
  await HttpHelpers.fromFile('report.pdf'),
  {
    headers: { 'content-type': 'application/pdf' },
  },
);

Request bodies are buffered, so a request can be replayed when it is retried.

Uploading files

postFormData sends a multipart/form-data request. Pass a record of string or Buffer fields, or a form-data FormData instance. The SDK sets the content-type header, including the boundary. Streams are not supported.

import { HttpHelpers } from '@sinch/sdk-core';

const response = await sinch.http.postFormData(
  'https://example.api.sinch.com/v1/uploads',
  {
    description: 'Monthly report',
    file: await HttpHelpers.fromFile('report.pdf'),
  },
);

A record does not set a filename. Use a FormData instance when the API expects one:

import FormData from 'form-data';
import { HttpHelpers } from '@sinch/sdk-core';

const form = new FormData();
form.append('description', 'Monthly report');
form.append('file', await HttpHelpers.fromFile('report.pdf'), {
  filename: 'report.pdf',
  contentType: 'application/pdf',
});

const response = await sinch.http.postFormData(
  'https://example.api.sinch.com/v1/uploads',
  form,
);

Request options

options overrides the client settings for a single request. Any option you don't set keeps the value of the client. These are the same fields as on SinchClient.

OptionDescriptionDefault
useSinchAuthfalse sends the request without the SDK authentication.true
timeoutSecondsTimeout of the request in seconds. 0 disables it.60
retryPolicyDEFAULT (honor Retry-After, otherwise exponential backoff), RETRY_AFTER, BACKOFF, or NONE.RetryPolicy.DEFAULT
maxRetryCountMaximum retries after the first attempt. Must be a non-negative integer.3
exponentialBackoffGrowth factor for the backoff ceiling (1000ms * exponentialBackoff^attempt).4

The defaults are the values used when neither the client nor the request options are set.

import { RetryPolicy } from '@sinch/sdk-core';

const response = await sinch.http.get(
  'https://example.api.sinch.com/v1/resource',
  {
    options: {
      timeoutSeconds: 30,
      retryPolicy: RetryPolicy.NONE,
    },
  },
);

Reading the response

Each method returns an HttpResponse with:

  • status: the HTTP status code.
  • headers: the response headers (HttpHeaders). Header names are case-insensitive, and getAll(name) returns every value of a repeated header.
  • content: the response body, readable with one of the methods below. asJson(), asString() and asBytes() are asynchronous and share one buffered copy.
MethodDescriptionExample
asJson()Returns the body parsed as JSON, or undefined if the body is empty.const resources = await response.content.asJson();
console.log(resources.items);
asString()Returns the body decoded with the charset of the content-type header, or UTF-8 if it declares none or an unknown one.const text = await response.content.asString();
console.log(text);
asBytes()Returns the body as a Buffer, without decoding.const data = await response.content.asBytes();
await writeFile('report.pdf', data);
asStream()Returns a Node.js readable stream for a large payload. Once the body has been read as a stream, the buffered readers can no longer be used.const stream = response.content.asStream();

Handling errors

A response with a status code of 400 or above throws an ApiHttpError (from @sinch/sdk-core). It extends RequestFailedError. The full response is still available on response, and statusCode is the HTTP status:

import { ApiHttpError } from '@sinch/sdk-core';

try {
  const response = await sinch.http.get(url);
} catch (error) {
  if (error instanceof ApiHttpError) {
    console.log(error.statusCode);
    console.log(await error.response.content.asString());
  }
}