A comprehensive Node.js SDK for the Twilio communications platform, enabling SMS, voice, video, and other communication services integration.
npx @tessl/cli install tessl/npm-twilio@5.9.00
# Twilio Node.js SDK
1
2
The Twilio Node.js SDK is a comprehensive library that provides a complete interface to the Twilio communications platform. It enables developers to integrate SMS, voice, video, chat, and other communication services into their Node.js applications with full TypeScript support and modern async/await patterns.
3
4
## Package Information
5
6
- **Package Name**: twilio
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install twilio`
10
11
## Core Imports
12
13
```typescript
14
import TwilioSDK from "twilio";
15
16
// Create client with auto-discovery of credentials
17
const client = TwilioSDK(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
18
19
// Access individual components via namespace properties
20
const {
21
Twilio,
22
jwt,
23
twiml,
24
validateRequest,
25
webhook,
26
ClientCredentialProviderBuilder,
27
OrgsCredentialProviderBuilder,
28
NoAuthCredentialProvider,
29
RestException,
30
RequestClient
31
} = TwilioSDK;
32
33
// Access nested components
34
const { AccessToken, ClientCapability, ValidationToken } = jwt;
35
const { VoiceResponse, MessagingResponse, FaxResponse } = twiml;
36
const { TaskRouterCapability, util } = jwt.taskrouter;
37
```
38
39
For CommonJS:
40
41
```javascript
42
const TwilioSDK = require("twilio");
43
const client = TwilioSDK(accountSid, authToken);
44
45
// Access components the same way
46
const { jwt, twiml, validateRequest } = TwilioSDK;
47
```
48
49
## Basic Usage
50
51
```typescript
52
import TwilioSDK from "twilio";
53
54
// Initialize the Twilio client
55
const client = TwilioSDK(
56
process.env.TWILIO_ACCOUNT_SID,
57
process.env.TWILIO_AUTH_TOKEN
58
);
59
60
// Send an SMS message
61
const message = await client.messages.create({
62
body: "Hello from Twilio!",
63
from: "+1234567890",
64
to: "+0987654321"
65
});
66
67
// Make a voice call
68
const call = await client.calls.create({
69
url: "http://demo.twilio.com/docs/voice.xml",
70
from: "+1234567890",
71
to: "+0987654321"
72
});
73
74
// Generate TwiML response
75
const { twiml } = TwilioSDK;
76
const response = new twiml.VoiceResponse();
77
response.say("Hello World");
78
console.log(response.toString());
79
```
80
81
## Architecture
82
83
The Twilio SDK is organized around several key architectural components:
84
85
- **REST Client**: The main `Twilio` class provides access to 38+ service domains through a unified interface
86
- **Service Domains**: Each Twilio service (messaging, voice, video, etc.) is exposed as a separate domain with its own resources and methods
87
- **TwiML Builders**: Declarative classes for generating Twilio Markup Language (TwiML) responses for webhooks
88
- **JWT Utilities**: Token generation and validation for client-side applications and capability management
89
- **Webhook Validation**: Security utilities for validating incoming Twilio requests
90
- **Credential Providers**: Flexible authentication strategies including OAuth2 and API keys
91
- **HTTP Client**: Advanced HTTP client with automatic retries, request signing, and comprehensive error handling
92
93
## Capabilities
94
95
### REST API Client
96
97
The core REST client providing access to all Twilio services including messaging, voice, video, and platform services. Supports automatic authentication, request retries, and comprehensive error handling.
98
99
```typescript { .api }
100
function TwilioSDK(
101
accountSid?: string,
102
authToken?: string,
103
opts?: ClientOpts
104
): Twilio;
105
106
interface ClientOpts {
107
httpClient?: RequestClient;
108
accountSid?: string;
109
env?: NodeJS.ProcessEnv;
110
edge?: string;
111
region?: string;
112
lazyLoading?: boolean;
113
logLevel?: string;
114
userAgentExtensions?: string[];
115
autoRetry?: boolean;
116
maxRetryDelay?: number;
117
maxRetries?: number;
118
timeout?: number;
119
keepAlive?: boolean;
120
}
121
```
122
123
[REST API Client](./rest-client.md)
124
125
### TwiML Generation
126
127
TwiML (Twilio Markup Language) builders for creating XML responses to handle incoming calls, messages, and faxes. Provides a fluent, type-safe interface for constructing complex call flows and messaging logic.
128
129
```typescript { .api }
130
class VoiceResponse {
131
constructor();
132
say(message?: string, attributes?: SayAttributes): Say;
133
play(url?: string, attributes?: PlayAttributes): Play;
134
gather(attributes?: GatherAttributes): Gather;
135
dial(number?: string, attributes?: DialAttributes): Dial;
136
record(attributes?: RecordAttributes): Record;
137
redirect(url?: string, attributes?: RedirectAttributes): Redirect;
138
pause(attributes?: PauseAttributes): Pause;
139
hangup(): Hangup;
140
reject(attributes?: RejectAttributes): Reject;
141
}
142
143
class MessagingResponse {
144
constructor();
145
message(body?: string, attributes?: MessageAttributes): Message;
146
redirect(url?: string, attributes?: RedirectAttributes): Redirect;
147
}
148
```
149
150
[TwiML Generation](./twiml.md)
151
152
### JWT Authentication
153
154
JWT token generation and validation for Twilio Client applications, TaskRouter workers, and service capabilities. Supports access tokens, client capabilities, and request validation.
155
156
```typescript { .api }
157
class AccessToken {
158
constructor(accountSid: string, keySid: string, secret: string, options?: AccessTokenOptions);
159
addGrant(grant: Grant): AccessToken;
160
toJwt(algorithm?: string): string;
161
}
162
163
class ClientCapability {
164
constructor(options: ClientCapabilityOptions);
165
addScope(scope: Scope): ClientCapability;
166
toJwt(): string;
167
}
168
```
169
170
[JWT Authentication](./jwt.md)
171
172
### Webhook Validation
173
174
Security utilities for validating incoming Twilio webhook requests to ensure they originate from Twilio servers. Includes signature validation and Express.js middleware support.
175
176
```typescript { .api }
177
function validateRequest(
178
authToken: string,
179
twilioSignature: string,
180
url: string,
181
params: object
182
): boolean;
183
184
function validateRequestWithBody(
185
authToken: string,
186
twilioSignature: string,
187
url: string,
188
body: string
189
): boolean;
190
191
function webhook(options?: WebhookOptions): (req: any, res: any, next: Function) => void;
192
```
193
194
[Webhook Validation](./webhooks.md)
195
196
### Credential Providers
197
198
Advanced authentication strategies for OAuth2, organizational accounts, and custom credential management. Enables flexible authentication patterns beyond basic username/password.
199
200
```typescript { .api }
201
class ClientCredentialProviderBuilder {
202
setClientId(clientId: string): ClientCredentialProviderBuilder;
203
setClientSecret(clientSecret: string): ClientCredentialProviderBuilder;
204
setTokenManager(tokenManager: TokenManager): ClientCredentialProviderBuilder;
205
build(): ClientCredentialProvider;
206
}
207
208
class NoAuthCredentialProvider {
209
constructor();
210
toAuthStrategy(): AuthStrategy;
211
}
212
```
213
214
[Credential Providers](./credential-providers.md)
215
216
### HTTP Client Utilities
217
218
Core utilities for HTTP request handling and error management used throughout the SDK.
219
220
```typescript { .api }
221
class RestException extends Error {
222
status: number;
223
code: number;
224
moreInfo: string;
225
detail: string;
226
227
constructor(response: any);
228
}
229
230
class RequestClient {
231
constructor(options?: RequestClientOptions);
232
request<T>(opts: RequestOpts): Promise<T>;
233
}
234
235
interface RequestClientOptions {
236
timeout?: number;
237
keepAlive?: boolean;
238
keepAliveMsecs?: number;
239
maxSockets?: number;
240
maxTotalSockets?: number;
241
maxFreeSockets?: number;
242
ca?: string | Buffer;
243
}
244
```
245
246
## Types
247
248
```typescript { .api }
249
interface ClientOpts {
250
httpClient?: RequestClient;
251
accountSid?: string;
252
env?: NodeJS.ProcessEnv;
253
edge?: string;
254
region?: string;
255
lazyLoading?: boolean;
256
logLevel?: string;
257
userAgentExtensions?: string[];
258
autoRetry?: boolean;
259
maxRetryDelay?: number;
260
maxRetries?: number;
261
validationClient?: ValidationClientOptions;
262
timeout?: number;
263
keepAlive?: boolean;
264
keepAliveMsecs?: number;
265
maxSockets?: number;
266
maxTotalSockets?: number;
267
maxFreeSockets?: number;
268
scheduling?: "fifo" | "lifo" | undefined;
269
ca?: string | Buffer;
270
}
271
272
interface RequestOpts {
273
method?: HttpMethod;
274
uri?: string;
275
username?: string;
276
password?: string;
277
authStrategy?: AuthStrategy;
278
headers?: Headers;
279
params?: object;
280
data?: object;
281
timeout?: number;
282
allowRedirects?: boolean;
283
logLevel?: string;
284
}
285
286
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "PATCH";
287
288
interface Headers {
289
[key: string]: string;
290
}
291
```