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.

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.
The following links are available for your reference:
You can install the Sinch Node.js SDK using either NPM or Yarn:
npm install @sinch/sdk-coreWhen 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 of the Node.js SDK client can be done in two ways, depending on which product you are using.
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.
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"
});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
});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"
});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"
});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
});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"
});The Node.js SDK currently supports the following products:
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.
/**
* 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()].
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'
});
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:
| API operation | SDK method |
|---|---|
| Rent the first available number matching the provided criteria | rentAny() |
| Rent a specified available phone number | rent() |
| Search for available phone numbers | list() |
| Checks the availability of a specific phone number | checkAvailability() |
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:
| API operation | SDK method |
|---|---|
| List active numbers for a project | list() |
| Update active number | update() |
| Retrieve active number | get() |
| Release active number | release() |
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 operation | SDK method |
|---|---|
| List available regions | list() |
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:
| API operation | SDK method |
|---|---|
| Get callbacks configuration | get() |
| Update callback configuration | update() |
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.
Response fields match the API responses. They are delivered as JavaScript objects.
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).
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()].
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"
}
}
});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 operation | SDK method |
|---|---|
| Send a message | send, or you could use any of the following message-specific methods: |
sendCardMessage | |
sendCarouselMessage | |
sendChoiceMessage | |
sendContactInfoMessage | |
sendListMessage | |
sendLocationMessage | |
sendMediaMessage | |
sendTemplateMessage | |
sendTextMessage | |
| Get a message | get |
| Delete a message | delete |
| List messages | list |
| Update a message's metadata | update |
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:
| API operation | SDK method |
|---|---|
| List all apps for a given project | list |
| Create an app | create |
| Get an app | get |
| Delete an app | delete |
| Update an app | update |
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 operation | SDK method |
|---|---|
| List contacts | list |
| Create a contact | create |
| Get a contact | get |
| Delete a contact | delete |
| Update a contact | update |
| Merge two contacts | mergeContact |
| Get channel profile | getChannelProfile |
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:
| API operation | SDK method |
|---|---|
| List conversations | list |
| Create a conversation | create |
| Get a conversation | get |
| Delete a conversation | delete |
| Update a conversation | update |
| Stop conversation | stopActive |
| Inject a message | injectMessage |
| Inject an event | injectEvent |
| List recent conversations | listRecent |
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 operation | SDK method |
|---|---|
| Send an event | send, or you could use any of the following message-specific methods: sendComposingEvent, sendComposingEndEvent, sendCommentReplyEvent, sendAgentJoinedEvent, sendAgentLeftEvent, or sendGenericEvent |
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 operation | SDK method |
|---|---|
| Transcode a message | transcodeMessage |
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 operation | SDK method |
|---|---|
| Capability lookup | lookup |
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:
| API operation | SDK method |
|---|---|
| List webhooks | list |
| Create a new webhook | create |
| Get a webhook | get |
| Update an existing webhook | update |
| Delete an existing webhook | delete |
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:
| API operation | SDK method |
|---|---|
| List all templates belonging to a project ID | list |
| Creates a template | create |
| Lists translations for a template | listTranslations |
| Updates a template | update |
| Get a template | get |
| Delete a template | delete |
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.
Response fields match the API responses. They are delivered as JavaScript objects.
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)
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.
// 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()].
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."
}
});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 operation | SDK method |
|---|---|
| Send | send() |
| List batches | list() |
| Dry run | dryRun() |
| Get a batch message | get() |
| Update a batch message | update() |
| Replace a batch | replace() |
| Cancel a batch message | cancel() |
| Send delivery feedback for a message | sendDeliveryFeedback() |
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:
| API operation | SDK method |
|---|---|
| Retrieve a delivery report | get() |
| Retrieve a recipient delivery report | getByPhoneNumber() |
| Retrieve a list of delivery reports | list() |
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 operation | SDK method |
|---|---|
| List groups | list() |
| Create a group | create() |
| Retrieve a group | get() |
| Update a group | update() |
| Replace a group | replace() |
| Delete a group | delete() |
| List group member phone numbers | listMembers() |
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 operation | SDK method |
|---|---|
| List incoming messages | list() |
| Retrieve inbound message | get() |
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 that the service_plan_id path parameter does not need to be included in any requests created by the Node.js SDK.
Response fields match the API responses. They are delivered as JavaScript objects.
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.
/**
* 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()].
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.'
}
}
});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:
| API operation | SDK method |
|---|---|
| Makes a Text-to-speech callout | tts() |
| Makes a Conference callout | conference() |
| Makes a Custom callout | custom() |
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 operation | SDK method |
|---|---|
| Get information about a call | get() |
Manage call with callLeg | manageWithCallLeg() |
| Updates a call in progress | update() |
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:
| API operation | SDK method |
|---|---|
| Get information about a conference | get() |
| Manage a conference participant | manageParticipant() |
| Remove a participant from a conference | kickParticipant() |
| Remove all participants from a conference | kickAll() |
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:
| API operation | SDK method |
|---|---|
| Return all the numbers assigned to an application | listNumbers() |
| Assign a number or list of numbers to an application | assignNumbers() |
| Unassign a number from an application | unassignNumber() |
| Return the callback URLs for an application | getCallbackUrls() |
| Update the callback URL for an application | updateCallbackUrls() |
| Returns information about a number | QueryNumber() |
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 event | Builder method name | Methods |
|---|---|---|
| Answered Call Event | AceSvamletBuilder() | setAction() or addInstruction() |
| Incoming Call Event | IceSvamletBuilder() | setAction() or addInstruction() |
| Prompt Input Event | PieSvamletBuilder() | setAction() or addInstruction() |
Using these builder methods you can then build your SVAML responses using the following methods:
Actions:
| Helper method name | Action |
|---|---|
Voice.aceActionHelper.connectConf | connectConf |
Voice.aceActionHelper.continue | continue |
Voice.aceActionHelper.hangup | hangup |
Voice.aceActionHelper.runMenu | runMenu |
Voice.iceActionHelper.connectConf | connectConf |
Voice.iceActionHelper.connectMxp | connectMxp |
Voice.iceActionHelper.connectPstn | connectPstn |
Voice.iceActionHelper.connectSip | connectSip |
Voice.iceActionHelper.hangup | hangup |
Voice.iceActionHelper.park | park |
Voice.iceActionHelper.runMenu | runMenu |
Voice.pieActionHelper.connectConf | connectConf |
Voice.pieActionHelper.connectSip | connectSip |
Voice.pieActionHelper.continue | continue |
Voice.pieActionHelper.hangup | hangup |
Voice.pieActionHelper.runMenu | runMenu |
Instructions:
| Helper method name | Action |
|---|---|
Voice.aceActionHelper.playFiles | playFiles |
Voice.aceActionHelper.say | say |
Voice.aceActionHelper.setCookie | setCookie |
Voice.aceActionHelper.startRecording | startRecording |
Voice.iceActionHelper.answer | answer |
Voice.iceActionHelper.playFiles | playFiles |
Voice.iceActionHelper.say | say |
Voice.iceActionHelper.sendDtmf | sendDtmf |
Voice.iceActionHelper.setCookie | setCookie |
Voice.iceActionHelper.startRecording | startRecording |
Voice.pieActionHelper.playFiles | playFiles |
Voice.pieActionHelper.say | say |
Voice.pieActionHelper.sendDtmf | sendDtmf |
Voice.pieActionHelper.setCookie | setCookie |
Voice.pieActionHelper.startRecording | startRecording |
Voice.pieActionHelper.stopRecording | stopRecording |
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.
Response fields match the API responses. They are delivered as Javascript objects.
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.
/**
* 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()].
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()}})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.
Response fields match the API responses. They are delivered as Javascript objects.
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.
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()].
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);
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:
| API operation | SDK method |
|---|---|
| Start an SMS PIN verification request | startSms() |
| Start a FlashCall verification request | startFlashCall() |
| Start a Phone Call verification request | startCallout() |
| Start a Data verification request | startSeamless() |
| Report an SMS verification PIN code by the identity of the recipient | reportSmsByIdentity() |
| Report a FlashCall verification code (CLI) by the identity of the recipient | reportFlashCallByIdentity() |
| Report a Phone Call verification code by the identity of the recipient | reportByCalloutIdentity() |
| Report an SMS verification PIN code by the ID of the verification request | reportSmsById() |
| Report a FlashCall verification code (CLI) by the ID of the verification request | reportFlashCallById() |
| Report a Phone Call verification code by the ID of the verification request | reportCalloutById() |
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:
| API operation | SDK method |
|---|---|
| Get the status of a verification by the ID of the verification request | getById() |
| Get the status of a verification by the identity of the recipient | getByIdentity() |
| Get the status of a verification by a reference value | getByReference() |
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 body | Helper method name | Parameters |
|---|---|---|
| Start SMS Verification | buildStartSmsVerificationRequest() |
|
| Start FlashCall Verification | buildStartFlashCallVerificationRequest() |
|
| Start Callout Verification | buildStartCalloutVerificationRequest() |
|
| Start Data Verification | buildStartSeamlessVerificationRequest() |
|
| Report SMS Verification by ID | buildReportSmsVerificationByIdRequest() |
|
| Report FlashCall Verification by ID | buildReportFlashCallVerificationByIdRequest() |
|
| Report Phone Call Verification by ID | buildReportCalloutVerificationByIdRequest() |
|
| Report SMS Verification by Identity | buildReportSmsVerificationByIdentityRequest() |
|
| Report FlashCall Verification by Identity | buildReportFlashCallVerificationByIdentityRequest() |
|
| Report Phone Call Verification by Identity | buildReportCalloutVerificationByIdentityRequest() |
|
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.
Response fields match the API responses. They are delivered as JavaScript objects.
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.
// 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()].
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' ],
},
});Response fields match the API responses. They are delivered as JavaScript objects.
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.
/**
* 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()].
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 }),
},
});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.
Response fields match the API responses. They are delivered as Javascript 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:
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 pageThe 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.
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.
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-Agentheader.
The HTTP client is available from version 1.9.0.
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.
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>.
| Method | Description |
|---|---|
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:
| Field | Description |
|---|---|
queryParams | The query string, as a URLSearchParams or as an already URL-encoded string. The leading ? is optional. |
headers | The request headers, as a record or as an HttpHeaders instance. Use an array of strings, or HttpHeaders.append, to repeat a header. |
options | Request-level settings that override the client settings for this request only. See Request options. |
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.
- OAuth2, when
keyIdandkeySecretare set. The access token is requested on the first call, cached and renewed when it expires. Any other credentials are ignored. - The SMS API token, when
apiTokenis set. - Application signing, when
applicationKeyandapplicationSecretare 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.
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.
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,
);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.
| Option | Description | Default |
|---|---|---|
useSinchAuth | false sends the request without the SDK authentication. | true |
timeoutSeconds | Timeout of the request in seconds. 0 disables it. | 60 |
retryPolicy | DEFAULT (honor Retry-After, otherwise exponential backoff), RETRY_AFTER, BACKOFF, or NONE. | RetryPolicy.DEFAULT |
maxRetryCount | Maximum retries after the first attempt. Must be a non-negative integer. | 3 |
exponentialBackoff | Growth 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,
},
},
);Each method returns an HttpResponse with:
status: the HTTP status code.headers: the response headers (HttpHeaders). Header names are case-insensitive, andgetAll(name)returns every value of a repeated header.content: the response body, readable with one of the methods below.asJson(),asString()andasBytes()are asynchronous and share one buffered copy.
| Method | Description | Example |
|---|---|---|
asJson() | Returns the body parsed as JSON, or undefined if the body is empty. | const resources = await response.content.asJson(); |
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(); |
asBytes() | Returns the body as a Buffer, without decoding. | const data = await response.content.asBytes(); |
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(); |
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());
}
}



