# Sinch Node.js SDK

![Node.js](https://img.shields.io/badge/node.js-blue.svg)
[![Latest Release](https://img.shields.io/npm/v/@sinch/sdk-core?label=%40sinch%2Fsdk-core&labelColor=FFC658)](https://www.npmjs.com/package/@sinch/sdk-core)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://github.com/sinch/sinch-sdk-node/blob/main/LICENSE)

Here you'll find documentation related to the Sinch Node SDK, including how to install it, initialize it, and start developing Node code using Sinch services.

To use Sinch services, you'll need a Sinch account and access keys. You can sign up for an account and create access keys at [dashboard.sinch.com](https://dashboard.sinch.com).

## Table of contents:

- [Prerequisites](#prerequisites)
- [Version support](#version-support)
- [Documentation](#documentation)
- [Installation](#installation)
- [Supported APIs](#supported-apis)
- [Getting started](#getting-started)
- [Logging](#logging)
- [Retry configuration](#retry-configuration)
- [Transport settings](#transport-settings)
- [Low-level HTTP client](#low-level-http-client)
- [Handling exceptions](#handling-exceptions)
- [Third-party dependencies](#third-party-dependencies)
- [Examples](#examples)
- [Changelog](#changelog)
- [License](#license)
- [Contact](#contact)


## Prerequisites

- Node.js [18.20.8](https://nodejs.org/en/download/archive/v18.20.8), [20.20.2](https://nodejs.org/en/download/archive/v20.20.2), or [22.23.0](https://nodejs.org/en/download/archive/v22.23.0) (LTS recommended)
- [npm](https://www.npmjs.com/) or [yarn](https://yarnpkg.com/) (recommended)
- [Sinch account](https://dashboard.sinch.com/)


> **Warning**:
This SDK is intended for server-side (backend) use only. Do not use it in front-end or client-side applications (web, mobile, or desktop), regardless of language or framework. Doing so can expose your Sinch credentials to end-users.


## Version support

This SDK follows [Semantic Versioning](https://semver.org/) for version numbering.
SemVer defines what changes are allowed in each type of release (major, minor, patch) but does not define a support or patching policy.

This section describes the support policy for this project.

**Release cadence**

A new major version will not be released until at least 6 months after the previous major version.

**Support policy**

Patches are published only for the latest minor release within each supported major version. For example: if version 2.0 exists and 2.1.0 is released, patches will be applied to 2.1.x only. Users on 2.0.x will no longer receive patches and must upgrade to 2.1.x to get bug fixes and security updates.

| Version | Status | Support | Timeline |
|  --- | --- | --- | --- |
| **Current major** (latest released) | Fully supported | All new features, bug fixes, and security fixes | Ongoing |
| **Previous major** | Maintenance | Critical bug fixes and security fixes only, no new features | Begins when current major is released; ends when next major is released or 1 year from current release, whichever comes first |
| **Older majors** | End-of-Life (EOL) | No patches or support | — |


**What are critical bug fixes?**

For the previous major version, we apply patches for:

- Security vulnerabilities
- Data loss risks
- Breaking compatibility issues


**If you're using an unsupported version**

We recommend upgrading to a supported version to receive ongoing security and stability updates. Bug reports against unsupported versions are not prioritized and may not be addressed.

**Dependency security updates**

We assess dependency vulnerabilities by severity level. High and Critical vulnerabilities (CVSS score ≥ 7.0) are backported to the latest minor release of both the current and previous major versions. Medium and Low severity vulnerabilities (CVSS < 7.0) are applied to the current major version only.

## Documentation

For more information on the SDK, refer to the dedicated [Node SDK documentation](https://developers.sinch.com/docs/sdks/node).

For the SDK's programmatic API surface, see the online [SDK reference](https://developers.sinch.com/sdk/sinch-sdk-node/latest).

For broader Sinch product documentation, including the underlying REST APIs, visit the official [Sinch developer portal](https://developers.sinch.com/).

## Installation

Run the following command to install the SDK:

```bash
npm init
npm install @sinch/sdk-core
```

If you want to use yarn as a package manager, run:

```bash
npm install --global yarn
yarn init
yarn add @sinch/sdk-core
```

## Supported APIs

| API Category | API Name |
|  --- | --- |
| Messaging | [Conversation API](https://developers.sinch.com/docs/conversation) |
|  | [SMS API](https://developers.sinch.com/docs/sms) |
|  | [Provisioning API](https://developers.sinch.com/docs/provisioning-api) |
| Voice and Video | [Voice API v2](https://developers.sinch.com/docs/voice-2.0), [Voice API v1](https://developers.sinch.com/docs/voice) |
|  | [Elastic SIP Trunking API](https://developers.sinch.com/docs/est) |
| Numbers | [Numbers API](https://developers.sinch.com/docs/numbers) |
| Verification | [Verification API](https://developers.sinch.com/docs/verification) |
|  | [Number Lookup API](https://developers.sinch.com/docs/number-lookup-api-v2) |
| Fax | [Fax API](https://developers.sinch.com/docs/fax) |


> **Note:** The SMS API is end-of-sale. New integrations should use the [Conversation API](https://developers.sinch.com/docs/conversation/) instead, which supports SMS and many other channels.


> **Note:** New projects should use [Voice API v2](https://developers.sinch.com/docs/voice-2.0). See [Voice API](#voice-api) for when to stay on v1.


> **Note:** Elastic SIP Trunking support is deprecated and will be removed in version 2 of the SDK.


## Getting started

The SDK is split across npm packages. Import `SinchClient` from [`@sinch/sdk-core`](https://github.com/sinch/sinch-sdk-node/blob/main/packages/sdk-core), which bundles all API packages. Each API lives in its own package, and all packages share the HTTP layer from [`@sinch/sdk-client`](https://github.com/sinch/sinch-sdk-node/blob/main/packages/sdk-client).

### Client initialization

To start using the SDK, initialize the main client class. This client gives you access to all the SDK services:

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

// Warning: not all APIs support project authentication. Check the section for each API before using this snippet.
const sinch = new SinchClient({
  projectId: process.env.SINCH_PROJECT_ID,
  keyId: process.env.SINCH_KEY_ID,
  keySecret: process.env.SINCH_KEY_SECRET,
});
```

Get `project_id`, `key_id` and `key_secret` from the [Access keys](https://dashboard.sinch.com/settings/access-keys) page in your Sinch dashboard (`key_secret` is shown only once, at creation time). It's highly recommended to not hardcode these credentials: load them from environment variables for local development, and from a secret manager in production.

This snippet is the common starting point for every API. Some APIs have a different initialization or need extra parameters (for example, a region), see the section for each API.

### Conversation API

The Conversation API is regionalized. To use this API, the `conversation_region` parameter is required:

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

const sinch = new SinchClient({
  projectId: process.env.SINCH_PROJECT_ID,
  keyId: process.env.SINCH_KEY_ID,
  keySecret: process.env.SINCH_KEY_SECRET,
  conversationRegion: 'us',
});
```

#### Callbacks

The Conversation API delivers asynchronous callbacks to the webhook URL you configure for your app in the [Conversation dashboard](https://dashboard.sinch.com/convapi/apps). `validateAuthenticationHeader` confirms a request comes from Sinch and `parseEvent` turns its payload into a typed callback object; `headers` and `rawBody` are the incoming request's headers and raw body:

```typescript
import { ConversationCallbackWebhooks } from '@sinch/sdk-core';

const callbackWebhooks = new ConversationCallbackWebhooks(process.env.SINCH_CONVERSATION_APP_SECRET);

const validated = callbackWebhooks.validateAuthenticationHeader(request.headers, request.rawBody);
if (!validated) {
  return res.status(401).send('Invalid webhook signature');
}

const event = callbackWebhooks.parseEvent(request.body);
```

`SINCH_CONVERSATION_APP_SECRET` is the app secret set per app in the [Conversation dashboard](https://dashboard.sinch.com/convapi/apps). `parseEvent` works without validating the request, but then its origin can't be verified, so validating is recommended in production.

You can find a complete example in the Conversation section of [examples/webhooks](https://github.com/sinch/sinch-sdk-node/blob/main/examples/webhooks/src/controller/app.controller.ts#L41-L61).

### SMS API

> **Warning:** the SMS API is end-of-sale. For new integrations, prefer the [Conversation API](#conversation-api).


The SMS API is regionalized: set `sms_region` to the region where your SMS account is hosted. The accepted values are `us`, `eu`, `au`, `br` and `ca`, and the region also determines which credentials you can use:

- **Project access keys** — available only in the `us` and `eu` regions. Use the same `project_id`, `key_id` and `key_secret` as the common client, plus `sms_region`:


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

const sinch = new SinchClient({
  projectId: process.env.SINCH_PROJECT_ID,
  keyId: process.env.SINCH_KEY_ID,
  keySecret: process.env.SINCH_KEY_SECRET,
  smsRegion: 'us',
});
```

> **SMS authentication for new projects**
Projects created after the SMS API end-of-sale (`15/04/26`) cannot use project access keys — the SMS API requests return `401 Unauthorized`.
If you encounter this issue, consider the following options:
1. Use service plan credentials (`service_plan_id` + `sms_api_token`)
2. Use the Conversation API, which works with project access keys.
3. Contact your account manager



- **Service plan** — available in all regions (`us`, `eu`, `au`, `br`, `ca`). Use a `service_plan_id` and `sms_api_token`, both available on the [Service APIs dashboard](https://dashboard.sinch.com/sms/api/services):


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

const sinch = new SinchClient({
  servicePlanId: process.env.SINCH_SERVICE_PLAN_ID,
  apiToken: process.env.SINCH_API_TOKEN,
  smsRegion: 'au',
});
```

> **Note:** if you use both the SMS and the [Conversation API](#conversation-api) from the same client, set `sms_region` and `conversation_region` to the same region. Mismatched regions cause delivery failures.


#### Callbacks

The SMS API delivers asynchronous callbacks to a webhook URL set per batch with the `callback_url` parameter on the send, update and replace operations. `validateAuthenticationHeader` confirms a request comes from Sinch and `parseEvent` turns its payload into a typed callback object; `headers` and `rawBody` are the incoming request's headers and raw body:

```typescript
import { SmsCallbackWebhooks } from '@sinch/sdk-core';

const callbackWebhooks = new SmsCallbackWebhooks(process.env.SINCH_SMS_APP_SECRET);

const validated = callbackWebhooks.validateAuthenticationHeader(request.headers, request.rawBody);
if (!validated) {
  return res.status(401).send('Invalid webhook signature');
}

const event = callbackWebhooks.parseEvent(request.body);
```

Signature authentication for SMS callbacks must be enabled for your account by your account manager. Until it is activated, signature headers will not be present and `parseEvent` can be called directly without signature validation. See the [SMS callbacks documentation](https://developers.sinch.com/docs/sms/api-reference/sms/tag/Webhooks/#tag/Webhooks/section/Callbacks).

You can find a complete example in [examples/webhooks](https://github.com/sinch/sinch-sdk-node/blob/main/examples/webhooks).

### Voice API

> **Note:** For all new projects, please use Voice API v2. This is especially important for projects involving:
- AI capabilities like Streams and Voice Relay
- Voice campaigns like Batch calling

You should only use the older Voice API v1 if one of the following is a strict requirement:
- The project must be in General Availability (GA).
- The project requires In-App voice or Conferencing (until these features are available in v2).



Voice API v2 uses the [common client](#client-initialization); methods are on `sinch.voice.v2`. Requests go to the global endpoint `https://voice.api.sinch.com` by default. If you need a specific regional endpoint, you can override it with the `voiceV2Hostname` client option.

Voice API v1 does not use project access keys. It authenticates with an `application_key` and `application_secret`, which you create per application in the [Voice dashboard](https://dashboard.sinch.com/voice/apps). Optionally set `voiceRegion` to select the regional endpoint:

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

const sinch = new SinchClient({
  applicationKey: process.env.SINCH_APPLICATION_KEY,
  applicationSecret: process.env.SINCH_APPLICATION_SECRET,
  voiceRegion: 'euc1',
});
```

#### Callbacks

Voice API v2 delivers asynchronous callbacks to the webhook URL configured on the Voice service. `validateAuthenticationHeader` confirms a request comes from Sinch and `parseEvent` turns its payload into a typed callback object; `headers`, `rawBody`, `path` and `method` are the incoming request's headers, raw body, path and HTTP method:

```typescript
import { VoiceV2CallbackWebhooks } from '@sinch/sdk-core';

const callbackWebhooks = new VoiceV2CallbackWebhooks({
  serviceId: process.env.SINCH_VOICE_SERVICE_ID,
  serviceSecret: process.env.SINCH_VOICE_SERVICE_SECRET,
});

const validated = callbackWebhooks.validateAuthenticationHeader(
  request.headers,
  request.rawBody,
  request.path,
  request.method,
);
if (!validated) {
  return res.status(401).send('Invalid authorization');
}

const event = callbackWebhooks.parseEvent(request.body);
```

`SINCH_VOICE_SERVICE_ID` and `SINCH_VOICE_SERVICE_SECRET` are the service ID and Base64 service secret issued for that Voice service. See the [Voice API v2 getting started guide](https://developers.sinch.com/docs/voice-2.0/getting-started).

Voice API v1 delivers asynchronous callbacks to the callback URL you configure for your application in the [Voice dashboard](https://dashboard.sinch.com/voice/apps). `validateAuthenticationHeader` confirms a request comes from Sinch and `parseEvent` turns its payload into a typed callback object; `headers`, `rawBody`, `path` and `method` are the incoming request's headers, raw body, path and HTTP method:

```typescript
import { VoiceCallbackWebhooks } from '@sinch/sdk-core';

const callbackWebhooks = new VoiceCallbackWebhooks({
  applicationKey: process.env.SINCH_APPLICATION_KEY,
  applicationSecret: process.env.SINCH_APPLICATION_SECRET,
});

const validated = callbackWebhooks.validateAuthenticationHeader(
  request.headers,
  request.rawBody,
  request.path,
  request.method,
);
if (!validated) {
  return res.status(401).send('Invalid authorization');
}

const event = callbackWebhooks.parseEvent(request.body);
```

You can find a complete example in [examples/webhooks](https://github.com/sinch/sinch-sdk-node/blob/main/examples/webhooks).

### Verification API

The Verification API uses the same application credentials as Voice API v1. Create an application in the [Verification dashboard](https://dashboard.sinch.com/verification/apps):

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

const sinch = new SinchClient({
  applicationKey: process.env.SINCH_APPLICATION_KEY,
  applicationSecret: process.env.SINCH_APPLICATION_SECRET,
});
```

#### Callbacks

The Verification API delivers asynchronous callbacks to the callback URL you configure for your application in the [Verification dashboard](https://dashboard.sinch.com/verification/apps). `validateAuthenticationHeader` confirms a request comes from Sinch and `parseEvent` turns its payload into a typed callback object; `headers`, `rawBody`, `path` and `method` are the incoming request's headers, raw body, path and HTTP method:

```typescript
import { VerificationCallbackWebhooks } from '@sinch/sdk-core';

const callbackWebhooks = new VerificationCallbackWebhooks({
  applicationKey: process.env.SINCH_APPLICATION_KEY,
  applicationSecret: process.env.SINCH_APPLICATION_SECRET,
});

const validated = callbackWebhooks.validateAuthenticationHeader(
  request.headers,
  request.rawBody,
  request.path,
  request.method,
);
if (!validated) {
  return res.status(401).send('Invalid authorization');
}

const event = callbackWebhooks.parseEvent(request.body);
```

You can find a complete example in [examples/webhooks](https://github.com/sinch/sinch-sdk-node/blob/main/examples/webhooks).

### Elastic SIP Trunking API

> **Warning:** Elastic SIP Trunking support is deprecated and will be removed in version 2 of the SDK.


The Elastic SIP Trunking API needs no extra parameters, use the [common client](#client-initialization) shown above.

### Provisioning API

The Provisioning API needs no extra parameters, use the [common client](#client-initialization) shown above.

### Numbers API

The Numbers API needs no extra parameters, use the [common client](#client-initialization) shown above.

#### Callbacks

The Numbers API delivers asynchronous callbacks to the callback URL you configure through `numbers.callbacks`. `validateAuthenticationHeader` confirms a request comes from Sinch and `parseEvent` turns its payload into a typed callback object; `headers` and `rawBody` are the incoming request's headers and raw body:

```typescript
import { NumbersCallbackWebhooks } from '@sinch/sdk-core';

const callbackWebhooks = new NumbersCallbackWebhooks(process.env.SINCH_NUMBERS_CALLBACK_SECRET);

const validated = callbackWebhooks.validateAuthenticationHeader(request.headers, request.rawBody);
if (!validated) {
  return res.status(401).send('Invalid signature');
}

const event = callbackWebhooks.parseEvent(request.body);
```

`SINCH_NUMBERS_CALLBACK_SECRET` is the `hmacSecret` returned by `numbers.callbacks.get()`. `parseEvent` works without validating the request, but then its origin can't be verified, so validating is recommended in production.

You can find a complete example in [examples/webhooks](https://github.com/sinch/sinch-sdk-node/blob/main/examples/webhooks).

### Number Lookup API

The Number Lookup API needs no extra parameters, use the [common client](#client-initialization) shown above.

### Fax API

The Fax API needs no extra parameters, use the [common client](#client-initialization) shown above.

#### Callbacks

The Fax API delivers asynchronous callbacks to the incoming webhook URL you configure per service in the [Fax dashboard](https://dashboard.sinch.com/fax/services). `parseEvent` turns the payload into a typed callback object:

```typescript
import { FaxCallbackWebhooks } from '@sinch/sdk-core';

const event = FaxCallbackWebhooks.parseEvent(request.body);
```

No request signature validation is implemented for the Fax API. You can find a complete example in [examples/webhooks](https://github.com/sinch/sinch-sdk-node/blob/main/examples/webhooks).

### Your first request

Once your client is configured, you can send your first message. The example below uses the Conversation API to send a simple text message over SMS. Replace CONVERSATION_APP_ID with your app ID and RECIPIENT_PHONE_NUMBER with the recipient's phone number:

```typescript
const response = await sinch.conversation.messages.send({
  sendMessageRequestBody: {
    app_id: CONVERSATION_APP_ID,
    message: {
      text_message: {
        text: '[Node.js SDK: Conversation Message] Sample text message',
      },
    },
    recipient: {
      identified_by: {
        channel_identities: [
          {
            channel: 'SMS',
            identity: 'RECIPIENT_PHONE_NUMBER',
          },
        ],
      },
    },
  },
});
```

## Logging

The SDK supports configurable logging through an optional `logger` property on `SinchClient` initialization parameters. Logging is handled by `@sinch/sdk-client`, the shared HTTP layer used by all API packages. Method contracts and log levels are defined on the [`Logger`](https://github.com/sinch/sinch-sdk-node/blob/main/packages/sdk-client/src/logger/logger-types.ts) interface.

- **Without a custom logger**: Omit `logger` to send SDK output to `console`, or pass `logger: null` to suppress it.
- **Lazy messages**: Each method accepts a [`LogMessage`](https://github.com/sinch/sinch-sdk-node/blob/main/packages/sdk-client/src/logger/logger-types.ts), a `string` or `() => string`. Pass a function to defer building the message until your logger reads it; level-aware loggers can then skip that work when the level is disabled.
- **Custom loggers**: Plug in any compatible logger, for example [Winston](https://www.npmjs.com/package/winston), and route SDK messages into your existing logging stack, format, and transports.


For a runnable example using Winston, see [examples/snippets/sdk-client/logger.js](https://github.com/sinch/sinch-sdk-node/blob/main/examples/snippets/sdk-client/logger.js).

## Retry configuration

When an API call or OAuth token request returns HTTP 429 (Too Many Requests), the SDK retries automatically. Configure this on `SinchClient`; the same settings apply to product API calls and token fetches.

| Field | Type | Default | Description |
|  --- | --- | --- | --- |
| `retryPolicy` | `RetryPolicy` | `DEFAULT` | `DEFAULT`: honor `Retry-After` when present, otherwise exponential backoff. `RETRY_AFTER`: retry only when a usable `Retry-After` header is present. `BACKOFF`: ignore `Retry-After` and use full-jitter exponential backoff. `NONE`: disable automatic retries. |
| `maxRetryCount` | `number` | `3` | Maximum retries after the first attempt before the error is surfaced to the caller. Must be a non-negative integer (`0` is allowed; decimals are rejected). |
| `exponentialBackoff` | `number` | `4` | Growth factor for the backoff ceiling (`1000ms * exponentialBackoff^attempt`). The wait is a random value between 0 and that ceiling. Must be a positive number (`> 0`; decimals are allowed). |


`Retry-After` may be a delay in seconds or an HTTP-date (RFC 7231). A small jitter (0–250 ms) is added so concurrent clients do not retry in lockstep. Invalid values are rejected.

### Retry settings

```typescript
import { SinchClient, RetryPolicy } from '@sinch/sdk-core';

const sinch = new SinchClient({
  ...,
  retryPolicy: RetryPolicy.BACKOFF,
  maxRetryCount: 5,
  exponentialBackoff: 2,
});
```

### Disable Retry Policy

To disable automatic retries (for example when an outer HTTP layer already honors `Retry-After`):

```typescript
const sinch = new SinchClient({
  ...,
  retryPolicy: RetryPolicy.NONE,
});
```

## Transport settings

`SinchClient` accepts optional transport-level settings on the same parameters object as credentials. They apply to product API calls and to OAuth token fetches.

| Field | Type | Default | Description |
|  --- | --- | --- | --- |
| `timeoutSeconds` | `number` | `60` | HTTP I/O timeout in seconds. Pass `0` to disable the timeout. Must be a non-negative number (`0` is allowed; negative values are rejected). |
| `useSinchAuth` | `boolean` | `true` | When `true`, the SDK authenticates the requests. Set `false` to disable it and supply your own `Authorization` header through `requestPlugins`: whatever the authentication method (OAuth2, SMS API token, Voice and Verification application signing), no authentication header is added and no credentials are required. The values used to build the URL are still required: `projectId` for the OAuth2 APIs (SMS included), or `servicePlanId` and `apiToken` to call the SMS API on its service plan URL. |


### Timeout

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

const sinch = new SinchClient({
  ...,
  timeoutSeconds: 30,
});
```

### Disable Sinch authentication

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

const sinch = new SinchClient({
  ...,
  useSinchAuth: false,
  requestPlugins: [/* custom Auth plugin */],
});
```

## Low-level HTTP client

`sinch.http` sends raw HTTP requests to any Sinch endpoint, including the ones not yet covered by the SDK (e.g. code generated from an OpenAPI specification). The SDK still takes care of:

- the authentication (`projectId` is not required: it is part of the URL), picked from the client credentials:
  - OAuth2 and its token cache when `keyId` and `keySecret` are set: it has priority, any other credentials are ignored
  - otherwise the SMS API token (`apiToken`) or the Voice / Verification application signing (`applicationKey` and `applicationSecret`): setting both of them without `keyId` and `keySecret` is a configuration error
- the HTTP 429 retries (see [Retry configuration](#retry-configuration))
- the timeout and the `User-Agent` header


Everything else is up to the caller: the URL, the query string and the body bytes are sent **untouched**. The URL is not validated, and the only change to the query string is the leading `?`, added when missing.

```typescript
import { SinchClient, RetryPolicy } from '@sinch/sdk-core';

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

const response = await sinch.http.get(
  `https://numbers.api.sinch.com/v1/projects/${projectId}/activeNumbers`,
  {
    queryParams: new URLSearchParams({ regionCode: 'US', type: 'LOCAL', pageSize: '5' }), // or a pre-encoded string
    headers: { accept: 'application/json' },
  },
);
const activeNumbers = await response.content.asJson();

await sinch.http.post(
  `https://lookup.api.sinch.com/v2/projects/${projectId}/lookups`,
  JSON.stringify({ number: '+14045001000' }),
  {
    headers: { 'content-type': 'application/json' },
    options: { timeoutSeconds: 10, retryPolicy: RetryPolicy.NONE }, // request-level overrides
  },
);
```

| Method | Body |
|  --- | --- |
| `get(url, params?)` / `delete(url, params?)` | none |
| `post(url, body?, params?)` / `put(...)` / `patch(...)` | optional: `string` | `Buffer` | `Uint8Array`. With a body, the `content-type` header is required: the call is rejected without it. 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). Use `HttpHelpers.fromFile(path)` to send a file. |
| `postFormData(url, form, params?)` | a `form-data` instance or a record of `string` / `Buffer` fields, sent as `multipart/form-data` (the SDK sets the `content-type` with its boundary) |


`params` holds `queryParams` (a `URLSearchParams` or a pre-encoded string, the leading `?` being optional), `headers` (a record or an `HttpHeaders` instance) and `options`, which override the client settings for this call only: `useSinchAuth`, `timeoutSeconds`, `retryPolicy`, `maxRetryCount` and `exponentialBackoff`. `useSinchAuth: false`, on the client or on the call, sends the request without any authentication header: set your own `Authorization` header. A call can disable the authentication but not enable it: with `useSinchAuth: false` on the client, no credentials are required and no call is authenticated.

The returned `HttpResponse` exposes `status`, `headers` and a lazy `content` parser: `asString()`, `asBytes()`, `asJson()` or `asStream()` (to download large payloads without buffering them). A status >= 400 is thrown as an `ApiHttpError`, whose `response` can still be read.

Known limitations:

- no automatic pagination, and no path segment or query parameter encoding
- field names are the raw ones from the API specification (no Date revival either)
- stream bodies are not supported, so the request can be replayed on retry


## Handling exceptions

Failed API calls throw typed errors from `@sinch/sdk-core`. The SDK validates every response automatically and raises an exception when the HTTP status is not successful or when the response body is empty or invalid.

| Error class | When it is thrown |
|  --- | --- |
| `RequestFailedError` | The API returned a non-success HTTP status (`statusCode` and `data` are available on the error) |
| `EmptyResponseError` | The response is missing or empty |
| `ResponseJSONParseError` | The response body could not be parsed as JSON |
| `ApiHttpError` | A [low-level HTTP client](#low-level-http-client) call returned a status >= 400 (extends `RequestFailedError`, adds the raw `response`) |
| `GenericError` | Other SDK-level errors |


```typescript
try {
  await sinchClient.sms.batches.send({
  sendSMSRequestBody: {
    body: 'Hello from the Sinch Node.js SDK!',
    to: ['+12065550100'],
    from: 'YOUR_sender_number',
  },
});
} catch (error) {
  if (error instanceof RequestFailedError) {
    console.error(`Request failed (${error.statusCode}):`, error.data);
  } else {
    console.error(error);
  }
}
```

## Third-party dependencies

The SDK relies on the following third-party dependencies:

- [node-fetch](https://www.npmjs.com/package/node-fetch): HTTP client used to send API requests.
- [form-data](https://www.npmjs.com/package/form-data): Multipart form-data support for file uploads.


## Examples

You can find:

- a JS example of each request in the [examples/snippets](https://github.com/sinch/sinch-sdk-node/blob/main/examples/snippets) folder.
- getting started guides for specific use cases in the [examples/getting-started](https://github.com/sinch/sinch-sdk-node/blob/main/examples/getting-started) folder.
- a TS example of each request in the [examples/simple-examples](https://github.com/sinch/sinch-sdk-node/blob/main/examples/simple-examples) folder.
- a Nest.js application for handling Sinch webhook callbacks in the [examples/webhooks](https://github.com/sinch/sinch-sdk-node/blob/main/examples/webhooks) folder.
- examples of integrated flows in the [examples/integrated-flows-examples](https://github.com/sinch/sinch-sdk-node/blob/main/examples/integrated-flows-examples) folder.


## Changelog

For information about the latest changes in the SDK, please refer to the [CHANGELOG](https://github.com/sinch/sinch-sdk-node/blob/main/packages/sdk-core/CHANGELOG.md) file.

## License

This project is licensed under the Apache License. See the [LICENSE](https://github.com/sinch/sinch-sdk-node/blob/main/LICENSE) file for the license text.

## Contact

Developer Experience engineering team: [team-developer-experience@sinch.com](mailto:team-developer-experience@sinch.com)

## Versions

- [1.9.0 (latest)](https://developers.sinch.com/sdk/sinch-sdk-node/1.9.0/index.html)
- [1.8.0](https://developers.sinch.com/sdk/sinch-sdk-node/1.8.0/index.html)
- [1.7.0](https://developers.sinch.com/sdk/sinch-sdk-node/1.7.0/index.html)
- [1.6.0](https://developers.sinch.com/sdk/sinch-sdk-node/1.6.0/index.html)
- [1.5.0](https://developers.sinch.com/sdk/sinch-sdk-node/1.5.0/index.html)
- [1.4.3](https://developers.sinch.com/sdk/sinch-sdk-node/1.4.3/index.html)
- [1.4.2](https://developers.sinch.com/sdk/sinch-sdk-node/1.4.2/index.html)
- [1.4.1](https://developers.sinch.com/sdk/sinch-sdk-node/1.4.1/index.html)
- [1.4.0](https://developers.sinch.com/sdk/sinch-sdk-node/1.4.0/index.html)
- [1.3.0](https://developers.sinch.com/sdk/sinch-sdk-node/1.3.0/index.html)
- [1.2.1](https://developers.sinch.com/sdk/sinch-sdk-node/1.2.1/index.html)
- [1.2.0](https://developers.sinch.com/sdk/sinch-sdk-node/1.2.0/index.html)
- [1.1.0](https://developers.sinch.com/sdk/sinch-sdk-node/1.1.0/index.html)
- [1.0.0](https://developers.sinch.com/sdk/sinch-sdk-node/1.0.0/index.html)
- [0.0.5](https://developers.sinch.com/sdk/sinch-sdk-node/0.0.5/index.html)
- [0.0.4](https://developers.sinch.com/sdk/sinch-sdk-node/0.0.4/index.html)
- [0.0.3](https://developers.sinch.com/sdk/sinch-sdk-node/0.0.3/index.html)
- [0.0.2](https://developers.sinch.com/sdk/sinch-sdk-node/0.0.2/index.html)
- [0.0.1](https://developers.sinch.com/sdk/sinch-sdk-node/0.0.1/index.html)