chub-dev 0.2.0-beta.2 → 0.2.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,946 +0,0 @@
1
- ---
2
- name: sdk
3
- description: "Cloud communications platform for SMS, voice, video, and WhatsApp messaging with programmable APIs"
4
- metadata:
5
- languages: "typescript"
6
- versions: "5.10.3"
7
- updated-on: "2025-09-25"
8
- source: maintainer
9
- tags: "twilio,sdk,sms,voice,communications"
10
- ---
11
- # Twilio Node.js Coding Guidelines
12
-
13
- You are a Twilio API coding expert. Help me with writing code using the Twilio Node.js library for building communication applications with SMS, voice calls, WhatsApp, and other messaging channels.
14
-
15
- Please follow the following guidelines when generating code.
16
-
17
- You can find the official SDK documentation and code samples here:
18
- https://www.twilio.com/docs/libraries/reference/twilio-node/
19
-
20
- ## Golden Rule: Use the Correct and Current SDK
21
-
22
- Always use the official Twilio Node.js library, which is the standard library for all Twilio API interactions.
23
-
24
- **Library Name:** Twilio Node.js Helper Library
25
- **NPM Package:** `twilio`
26
- **Supported Node.js Versions:** Node.js 14, 16, 18, 20, and LTS(22)
27
-
28
- **Installation:**
29
- - **Correct:** `npm install twilio` or `yarn add twilio`
30
-
31
- **APIs and Usage:**
32
- - **Correct:** `const client = require('twilio')(accountSid, authToken)`
33
- - **Correct:** `client.messages.create({...})` for SMS/MMS
34
- - **Correct:** `client.calls.create({...})` for voice calls
35
- - **Incorrect:** Using legacy or unofficial Twilio libraries
36
- - **Incorrect:** Exposing credentials in front-end applications
37
-
38
- ## Authentication and Initialization
39
-
40
- The Twilio Node.js library requires your Account SID and Auth Token for authentication.
41
-
42
- ### Environment Variables (Recommended)
43
-
44
- Set up environment variables for secure credential management:
45
-
46
- ```javascript
47
- // Uses TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN environment variables
48
- const client = require('twilio')();
49
-
50
- // Or explicitly pass credentials
51
- const accountSid = process.env.TWILIO_ACCOUNT_SID;
52
- const authToken = process.env.TWILIO_AUTH_TOKEN;
53
- const client = require('twilio')(accountSid, authToken);
54
- ```
55
-
56
- ### Client Configuration Options
57
-
58
- The Twilio client supports various configuration options:
59
-
60
- ```javascript
61
- const client = require('twilio')(accountSid, authToken, {
62
- lazyLoading: false, // Disable lazy loading for faster initial loads
63
- autoRetry: true, // Enable automatic retry with exponential backoff
64
- maxRetries: 3, // Maximum number of retries
65
- timeout: 30000, // HTTPS agent socket timeout in milliseconds
66
- keepAlive: true, // Enable connection reuse
67
- keepAliveMsecs: 1000, // Keep-alive timeout
68
- maxSockets: 20, // Maximum number of sockets
69
- region: 'au1', // Specify region for Global Infrastructure
70
- edge: 'sydney', // Specify edge location
71
- logLevel: 'debug' // Enable debug logging
72
- });
73
- ```
74
-
75
- ## Core Messaging (SMS/MMS)
76
-
77
- ### Basic SMS Messaging
78
-
79
- Send SMS messages using the Messages API:
80
-
81
- ```javascript
82
- const client = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
83
-
84
- async function sendSMS() {
85
- try {
86
- const message = await client.messages.create({
87
- body: 'Hello from Twilio!',
88
- to: '+1234567890', // Recipient's phone number in E.164 format
89
- from: '+0987654321' // Your Twilio phone number
90
- });
91
- console.log(`Message sent with SID: ${message.sid}`);
92
- } catch (error) {
93
- console.error('Error sending SMS:', error);
94
- }
95
- }
96
- ```
97
-
98
- ### MMS with Media
99
-
100
- Send MMS messages with media attachments:
101
-
102
- ```javascript
103
- async function sendMMS() {
104
- const message = await client.messages.create({
105
- body: 'Check out this image!',
106
- to: '+1234567890',
107
- from: '+0987654321',
108
- mediaUrl: [
109
- 'https://example.com/image.jpg',
110
- 'https://example.com/video.mp4'
111
- ]
112
- });
113
- console.log(`MMS sent with SID: ${message.sid}`);
114
- }
115
- ```
116
-
117
- ### WhatsApp Messaging
118
-
119
- Send WhatsApp messages using channel addressing:
120
-
121
- ```javascript
122
- async function sendWhatsApp() {
123
- const message = await client.messages.create({
124
- body: 'Hello via WhatsApp!',
125
- to: 'whatsapp:+1234567890',
126
- from: 'whatsapp:+0987654321'
127
- });
128
- console.log(`WhatsApp message sent: ${message.sid}`);
129
- }
130
- ```
131
-
132
- ### Using Messaging Services
133
-
134
- Use Messaging Services for better delivery and sender pool management:
135
-
136
- ```javascript
137
- async function sendWithMessagingService() {
138
- const message = await client.messages.create({
139
- body: 'Hello from Messaging Service!',
140
- to: '+1234567890',
141
- messagingServiceSid: 'MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
142
- // 'from' parameter is optional when using Messaging Service
143
- });
144
- }
145
- ```
146
-
147
- ## Voice Calls
148
-
149
- ### Making Phone Calls
150
-
151
- Create outbound calls using the Calls API:
152
-
153
- ```javascript
154
- async function makeCall() {
155
- try {
156
- const call = await client.calls.create({
157
- to: '+1234567890', // Number to call
158
- from: '+0987654321', // Your Twilio number
159
- url: 'https://example.com/twiml', // TwiML instructions URL
160
- method: 'POST', // HTTP method for TwiML URL
161
- statusCallback: 'https://example.com/status',
162
- statusCallbackEvent: ['initiated', 'ringing', 'answered', 'completed'],
163
- timeout: 30, // Ring timeout in seconds
164
- record: true // Record the call
165
- });
166
- console.log(`Call initiated with SID: ${call.sid}`);
167
- } catch (error) {
168
- console.error('Error making call:', error);
169
- }
170
- }
171
- ```
172
-
173
- ### Using TwiML Directly
174
-
175
- Pass TwiML instructions directly without external URLs:
176
-
177
- ```javascript
178
- const twilio = require('twilio');
179
- const VoiceResponse = twilio.twiml.VoiceResponse;
180
-
181
- async function makeCallWithTwiML() {
182
- const twiml = new VoiceResponse();
183
- twiml.say('Hello! This is a call from Twilio.');
184
- twiml.hangup();
185
-
186
- const call = await client.calls.create({
187
- to: '+1234567890',
188
- from: '+0987654321',
189
- twiml: twiml.toString()
190
- });
191
- }
192
- ```
193
-
194
- ## TwiML Generation
195
-
196
- ### Voice TwiML
197
-
198
- Generate TwiML for voice applications:
199
-
200
- ```javascript
201
- const twilio = require('twilio');
202
- const VoiceResponse = twilio.twiml.VoiceResponse;
203
-
204
- function generateVoiceTwiML() {
205
- const twiml = new VoiceResponse();
206
-
207
- // Text-to-speech
208
- twiml.say({
209
- voice: 'alice',
210
- language: 'en-US'
211
- }, 'Hello, thanks for calling!');
212
-
213
- // Play audio file
214
- twiml.play('https://example.com/welcome.mp3');
215
-
216
- // Gather user input
217
- const gather = twiml.gather({
218
- numDigits: 1,
219
- action: '/process-input',
220
- method: 'POST'
221
- });
222
- gather.say('Press 1 for sales, 2 for support');
223
-
224
- // Dial another number
225
- twiml.dial('+1234567890');
226
-
227
- return twiml.toString();
228
- }
229
- ```
230
-
231
- ### Advanced Voice Features
232
-
233
- Use advanced voice capabilities:
234
-
235
- ```javascript
236
- function advancedVoiceTwiML() {
237
- const twiml = new VoiceResponse();
238
-
239
- // Conference calling
240
- const dial = twiml.dial();
241
- dial.conference('Customer Support Conference');
242
-
243
- // Record call
244
- twiml.record({
245
- action: '/handle-recording',
246
- method: 'POST',
247
- maxLength: 30,
248
- transcribe: true
249
- });
250
-
251
- // Connect to client/browser
252
- const dial2 = twiml.dial();
253
- dial2.client('john');
254
-
255
- return twiml.toString();
256
- }
257
- ```
258
-
259
- ### Messaging TwiML
260
-
261
- Generate TwiML responses for incoming messages:
262
-
263
- ```javascript
264
- const MessagingResponse = twilio.twiml.MessagingResponse;
265
-
266
- function generateMessagingTwiML() {
267
- const twiml = new MessagingResponse();
268
- twiml.message('Thanks for your message! We will get back to you soon.');
269
- return twiml.toString();
270
- }
271
- ```
272
-
273
- ## Webhook Handling and Validation
274
-
275
- ### Express.js Webhook Integration
276
-
277
- Handle and validate incoming Twilio webhooks:
278
-
279
- ```javascript
280
- const express = require('express');
281
- const twilio = require('twilio');
282
-
283
- const app = express();
284
- app.use(express.urlencoded({ extended: false }));
285
-
286
- // Webhook validation
287
- function validateTwilioSignature(req, res, next) {
288
- const twilioSignature = req.headers['x-twilio-signature'];
289
- const params = req.body;
290
- const url = `https://${req.headers.host}${req.originalUrl}`;
291
-
292
- const isValid = twilio.validateRequest(
293
- process.env.TWILIO_AUTH_TOKEN,
294
- twilioSignature,
295
- url,
296
- params
297
- );
298
-
299
- if (!isValid) {
300
- return res.status(403).send('Forbidden');
301
- }
302
- next();
303
- }
304
-
305
- // Handle incoming calls
306
- app.post('/voice', validateTwilioSignature, (req, res) => {
307
- const twiml = new twilio.twiml.VoiceResponse();
308
- twiml.say('Hello from your webhook!');
309
- res.type('text/xml');
310
- res.send(twiml.toString());
311
- });
312
-
313
- // Handle incoming messages
314
- app.post('/sms', validateTwilioSignature, (req, res) => {
315
- const twiml = new twilio.twiml.MessagingResponse();
316
- const incomingMessage = req.body.Body;
317
-
318
- if (incomingMessage.toLowerCase() === 'hello') {
319
- twiml.message('Hi there! How can I help you?');
320
- } else {
321
- twiml.message('Thanks for your message!');
322
- }
323
-
324
- res.type('text/xml');
325
- res.send(twiml.toString());
326
- });
327
- ```
328
-
329
- ### Webhook Validation Utilities
330
-
331
- Use built-in validation helpers:
332
-
333
- ```javascript
334
- // For Express.js
335
- const isValid = twilio.validateExpressRequest(req, authToken);
336
-
337
- // For general request validation
338
- const isValid = twilio.validateRequest(
339
- authToken,
340
- twilioSignature,
341
- url,
342
- params
343
- );
344
-
345
- // Validate request with body
346
- const isValid = twilio.validateRequestWithBody(
347
- authToken,
348
- twilioSignature,
349
- url,
350
- body
351
- );
352
- ```
353
-
354
- ## Error Handling and Debugging
355
-
356
- ### Exception Handling
357
-
358
- Handle Twilio API errors gracefully:
359
-
360
- ```javascript
361
- // With promises
362
- client.messages.create({
363
- body: 'Hello from Node',
364
- to: '+12345678901',
365
- from: '+12345678901',
366
- })
367
- .then((message) => console.log(message))
368
- .catch((error) => {
369
- console.log(error.code); // Twilio error code
370
- console.log(error.message); // Error message
371
- console.log(error.status); // HTTP status code
372
- });
373
-
374
- // With async/await
375
- try {
376
- const message = await client.messages.create({
377
- body: 'Hello from Node',
378
- to: '+12345678901',
379
- from: '+12345678901',
380
- });
381
- console.log(message);
382
- } catch (error) {
383
- console.error('Twilio Error:', error.code, error.message);
384
- }
385
- ```
386
-
387
- ### Debug Logging
388
-
389
- Enable debug logging to troubleshoot issues:
390
-
391
- ```javascript
392
- // Via environment variable
393
- process.env.TWILIO_LOG_LEVEL = 'debug';
394
-
395
- // Via client configuration
396
- const client = require('twilio')(accountSid, authToken, {
397
- logLevel: 'debug'
398
- });
399
-
400
- // Set after client creation
401
- client.logLevel = 'debug';
402
- ```
403
-
404
- ### Request/Response Debugging
405
-
406
- Access underlying request and response details:
407
-
408
- ```javascript
409
- client.messages.create({
410
- to: '+14158675309',
411
- from: '+14258675310',
412
- body: 'Ahoy!',
413
- })
414
- .then(() => {
415
- // Access request details
416
- console.log(client.lastRequest.method);
417
- console.log(client.lastRequest.url);
418
- console.log(client.lastRequest.auth);
419
- console.log(client.lastRequest.params);
420
- console.log(client.lastRequest.headers);
421
- console.log(client.lastRequest.data);
422
-
423
- // Access response details
424
- console.log(client.httpClient.lastResponse.statusCode);
425
- console.log(client.httpClient.lastResponse.body);
426
- });
427
- ```
428
-
429
- ## Advanced Features
430
-
431
- ### Pagination and Resource Iteration
432
-
433
- Handle large result sets efficiently:
434
-
435
- ```javascript
436
- // List all messages (with automatic pagination)
437
- const messages = await client.messages.list({
438
- from: '+1234567890',
439
- limit: 100
440
- });
441
-
442
- // Stream through messages efficiently
443
- client.messages.each({
444
- from: '+1234567890',
445
- pageSize: 50
446
- }, (message) => {
447
- console.log(`Message: ${message.sid} - ${message.body}`);
448
- });
449
-
450
- // Manual pagination
451
- let messages = await client.messages.page({
452
- from: '+1234567890',
453
- pageSize: 20
454
- });
455
-
456
- while (messages.instances.length > 0) {
457
- messages.instances.forEach(message => {
458
- console.log(message.body);
459
- });
460
-
461
- if (messages.nextPageUrl) {
462
- messages = await messages.nextPage();
463
- } else {
464
- break;
465
- }
466
- }
467
- ```
468
-
469
- ### Subaccount Management
470
-
471
- Work with main accounts and subaccounts:
472
-
473
- ```javascript
474
- const accountSid = process.env.TWILIO_ACCOUNT_SID;
475
- const authToken = process.env.TWILIO_AUTH_TOKEN;
476
- const subaccountSid = process.env.TWILIO_SUBACCOUNT_SID;
477
-
478
- const client = require('twilio')(accountSid, authToken);
479
-
480
- // Operations on main account (default)
481
- const mainAccountCalls = await client.api.v2010.account.calls.list();
482
-
483
- // Operations on subaccount
484
- const subaccountCalls = await client.api.v2010.account(subaccountSid).calls.list();
485
- ```
486
-
487
- ### Auto-Retry Configuration
488
-
489
- Configure automatic retry with exponential backoff:
490
-
491
- ```javascript
492
- const client = require('twilio')(accountSid, authToken, {
493
- autoRetry: true, // Enable auto-retry on 429 errors
494
- maxRetries: 3 // Maximum number of retries
495
- });
496
- ```
497
-
498
- ### Connection Management
499
-
500
- Configure HTTP agent options for connection reuse:
501
-
502
- ```javascript
503
- const client = require('twilio')(accountSid, authToken, {
504
- timeout: 30000, // Socket timeout in milliseconds
505
- keepAlive: true, // Enable connection reuse
506
- keepAliveMsecs: 1000, // Keep-alive timeout
507
- maxSockets: 20, // Maximum number of sockets
508
- maxTotalSockets: 100, // Maximum total sockets
509
- maxFreeSockets: 5, // Maximum free sockets
510
- scheduling: "lifo" // Socket scheduling
511
- });
512
- ```
513
-
514
- ### Global Infrastructure
515
-
516
- Target specific regions and edges:
517
-
518
- ```javascript
519
- // Set during client initialization
520
- const client = require('twilio')(accountSid, authToken, {
521
- region: 'au1',
522
- edge: 'sydney'
523
- });
524
-
525
- // Or set after client creation
526
- client.region = 'au1';
527
- client.edge = 'sydney';
528
- ```
529
-
530
- ## Security Best Practices
531
-
532
- ### Environment Variables
533
-
534
- Never hardcode credentials in your application:
535
-
536
- ```javascript
537
- // Good - Use environment variables
538
- const accountSid = process.env.TWILIO_ACCOUNT_SID;
539
- const authToken = process.env.TWILIO_AUTH_TOKEN;
540
-
541
- // Bad - Hardcoded credentials
542
- const accountSid = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
543
- const authToken = 'your_auth_token';
544
- ```
545
-
546
- ### SSL Certificate Validation
547
-
548
- Configure SSL bundle if needed:
549
-
550
- ```javascript
551
- // Set CA bundle path via environment variable
552
- process.env.TWILIO_CA_BUNDLE = '/path/to/ca-bundle.crt';
553
- ```
554
-
555
- ### Frontend Security Warning
556
-
557
- Never use this library in frontend applications:
558
-
559
- ## Common Integration Patterns
560
-
561
- ### Message Status Tracking
562
-
563
- Track message delivery status:
564
-
565
- ```javascript
566
- async function sendAndTrackMessage() {
567
- const message = await client.messages.create({
568
- body: 'Hello World!',
569
- to: '+1234567890',
570
- from: '+0987654321',
571
- statusCallback: 'https://yourapp.com/sms-status'
572
- });
573
-
574
- // Later, check message status
575
- const updatedMessage = await client.messages(message.sid).fetch();
576
- console.log(`Message status: ${updatedMessage.status}`);
577
- }
578
- ```
579
-
580
- ### Call Recording and Transcription
581
-
582
- Record and transcribe calls:
583
-
584
- ```javascript
585
- async function makeRecordedCall() {
586
- const call = await client.calls.create({
587
- to: '+1234567890',
588
- from: '+0987654321',
589
- url: 'https://yourapp.com/twiml',
590
- record: true,
591
- recordingStatusCallback: 'https://yourapp.com/recording-status'
592
- });
593
- }
594
- ```
595
-
596
- ## OAuth Support (Beta)
597
-
598
- The library supports OAuth 2.0 authentication:
599
-
600
- ```javascript
601
- // OAuth with Client Credentials Flow
602
- const client = twilio.ClientCredentialProviderBuilder()
603
- .username('your_api_key')
604
- .password('your_api_secret')
605
- .accountSid('your_account_sid')
606
- .build();
607
- ```
608
-
609
- ## TypeScript Support
610
-
611
- The library includes TypeScript definitions:
612
-
613
- ```typescript
614
- import twilio from 'twilio';
615
-
616
- const client = twilio(process.env.TWILIO_ACCOUNT_SID!, process.env.TWILIO_AUTH_TOKEN!);
617
-
618
- interface MessageOptions {
619
- body: string;
620
- to: string;
621
- from: string;
622
- }
623
-
624
- async function sendTypedMessage(options: MessageOptions): Promise<string> {
625
- const message = await client.messages.create(options);
626
- return message.sid;
627
- }
628
- ```
629
-
630
- ## Error Codes and Troubleshooting
631
-
632
- Common error scenarios to handle:
633
-
634
- - **20003**: Authentication failed - check credentials
635
- - **21211**: Invalid phone number format - use E.164 format
636
- - **21608**: Phone number not verified - verify number first
637
- - **30034**: Message delivery failed - recipient carrier issue
638
-
639
- ## Useful Links
640
-
641
- - **Documentation**: https://www.twilio.com/docs/libraries/reference/twilio-node/
642
- - **API Reference**: https://www.twilio.com/docs/api
643
- - **Console**: https://console.twilio.com
644
- - **TwiML Reference**: https://www.twilio.com/docs/voice/twiml
645
- - **Error Codes**: https://www.twilio.com/docs/api/errors
646
- - **Support**: https://support.twilio.com
647
-
648
- ## Notes
649
-
650
- This guide covers the core functionality of the Twilio Node.js library. The library is auto-generated from Twilio's OpenAPI specifications, ensuring it stays current with API changes. For the most up-to-date information and additional services not covered here, refer to the official documentation.
651
-
652
- ## Official Documentation
653
-
654
- # twilio-node
655
-
656
- This library supports the following Node.js implementations:
657
-
658
- - Node.js 14
659
- - Node.js 16
660
- - Node.js 18
661
- - Node.js 20
662
- - Node.js lts(22)
663
-
664
- TypeScript is supported for TypeScript version 2.9 and above.
665
-
666
- > **Warning**
667
- > Do not use this Node.js library in a front-end application. Doing so can expose your Twilio credentials to end-users as part of the bundled HTML/JavaScript sent to their browser.
668
-
669
- `npm install twilio` or `yarn add twilio`
670
-
671
- ```javascript
672
- // Your AccountSID and Auth Token from console.twilio.com
673
- const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
674
- const authToken = 'your_auth_token';
675
- ```
676
-
677
- ```javascript
678
- const client = require('twilio')(accountSid, authToken);
679
- ```
680
-
681
- ```javascript
682
- client.messages
683
- .create({
684
- body: 'Hello from twilio-node',
685
- to: '+12345678901', // Text your number
686
- from: '+12345678901', // From a valid Twilio number
687
- })
688
- .then((message) => console.log(message.sid));
689
- ```
690
-
691
- > **Warning**
692
- > It's okay to hardcode your credentials when testing locally, but you should use environment variables to keep them secret before committing any code or deploying to production. Check out [How to Set Environment Variables](https://www.twilio.com/blog/2017/01/how-to-set-environment-variables.html) for more information.
693
-
694
- ## OAuth Feature for Twilio APIs
695
- We are introducing Client Credentials Flow-based OAuth 2.0 authentication. This feature is currently in beta and its implementation is subject to change.
696
-
697
- API examples [here](https://github.com/twilio/twilio-node/blob/main/examples/public_oauth.js)
698
-
699
- Organisation API examples [here](https://github.com/twilio/twilio-node/blob/main/examples/orgs_api.js)
700
-
701
- `twilio-node` supports credential storage in environment variables. If no credentials are provided when instantiating the Twilio client (e.g., `const client = require('twilio')();`), the values in following env vars will be used: `TWILIO_ACCOUNT_SID` and `TWILIO_AUTH_TOKEN`.
702
-
703
- If your environment requires SSL decryption, you can set the path to CA bundle in the env var `TWILIO_CA_BUNDLE`.
704
-
705
- If you invoke any V2010 operations without specifying an account SID, `twilio-node` will automatically use the `TWILIO_ACCOUNT_SID` value that the client was initialized with. This is useful for when you'd like to, for example, fetch resources for your main account but also your subaccount. See below:
706
-
707
- ```javascript
708
- // Your Account SID, Subaccount SID Auth Token from console.twilio.com
709
- const accountSid = process.env.TWILIO_ACCOUNT_SID;
710
- const authToken = process.env.TWILIO_AUTH_TOKEN;
711
- const subaccountSid = process.env.TWILIO_ACCOUNT_SUBACCOUNT_SID;
712
-
713
- const client = require('twilio')(accountSid, authToken);
714
- const mainAccountCalls = client.api.v2010.account.calls.list; // SID not specified, so defaults to accountSid
715
- const subaccountCalls = client.api.v2010.account(subaccountSid).calls.list; // SID specified as subaccountSid
716
- ```
717
-
718
- ```javascript
719
- const client = require('twilio')(accountSid, authToken, {
720
- lazyLoading: false,
721
- });
722
- ```
723
-
724
- ### Enable Auto-Retry with Exponential Backoff
725
-
726
- `twilio-node` supports automatic retry with exponential backoff when API requests receive an [Error 429 response](https://support.twilio.com/hc/en-us/articles/360044308153-Twilio-API-response-Error-429-Too-Many-Requests-). This retry with exponential backoff feature is disabled by default. To enable this feature, instantiate the Twilio client with the `autoRetry` flag set to `true`.
727
-
728
- Optionally, the maximum number of retries performed by this feature can be set with the `maxRetries` flag. The default maximum number of retries is `3`.
729
-
730
- ```javascript
731
- const accountSid = process.env.TWILIO_ACCOUNT_SID;
732
- const authToken = process.env.TWILIO_AUTH_TOKEN;
733
-
734
- const client = require('twilio')(accountSid, authToken, {
735
- autoRetry: true,
736
- maxRetries: 3,
737
- });
738
- ```
739
-
740
- ```
741
- ### Set HTTP Agent Options
742
-
743
- `twilio-node` allows you to set HTTP Agent Options in the Request Client. This feature allows you to re-use your connections. To enable this feature, instantiate the Twilio client with the `keepAlive` flag set to `true`.
744
-
745
- Optionally, the socket timeout and maximum number of sockets can also be set. See the example below:
746
-
747
- ```javascript
748
- const accountSid = process.env.TWILIO_ACCOUNT_SID;
749
- const authToken = process.env.TWILIO_AUTH_TOKEN;
750
-
751
- const client = require('twilio')(accountSid, authToken, {
752
- timeout: 30000, // HTTPS agent's socket timeout in milliseconds, default is 30000
753
- keepAlive: true, // https.Agent keepAlive option, default is false
754
- keepAliveMsecs: 1000, // https.Agent keepAliveMsecs option in milliseconds, default is 1000
755
- maxSockets: 20, // https.Agent maxSockets option, default is 20
756
- maxTotalSockets: 100, // https.Agent maxTotalSockets option, default is 100
757
- maxFreeSockets: 5, // https.Agent maxFreeSockets option, default is 5
758
- scheduling: "lifo", // https.Agent scheduling option, default is 'lifo'
759
- });
760
- ```
761
- ```
762
-
763
- ```
764
- ### Specify Region and/or Edge
765
-
766
- To take advantage of Twilio's [Global Infrastructure](https://www.twilio.com/docs/global-infrastructure), specify the target Region and/or Edge for the client:
767
-
768
- ```javascript
769
- const accountSid = process.env.TWILIO_ACCOUNT_SID;
770
- const authToken = process.env.TWILIO_AUTH_TOKEN;
771
-
772
- const client = require('twilio')(accountSid, authToken, {
773
- region: 'au1',
774
- edge: 'sydney',
775
- });
776
- ```
777
-
778
- Alternatively, specify the edge and/or region after constructing the Twilio client:
779
-
780
- ```javascript
781
- const client = require('twilio')(accountSid, authToken);
782
- client.region = 'au1';
783
- client.edge = 'sydney';
784
- ```
785
-
786
- This will result in the `hostname` transforming from `api.twilio.com` to `api.sydney.au1.twilio.com`.
787
- ```
788
-
789
- ```
790
- ### Iterate through records
791
-
792
- The library automatically handles paging for you. Collections, such as `calls` and `messages`, have `list` and `each` methods that page under the hood. With both `list` and `each`, you can specify the number of records you want to receive (`limit`) and the maximum size you want each page fetch to be (`pageSize`). The library will then handle the task for you.
793
-
794
- `list` eagerly fetches all records and returns them as a list, whereas `each` streams records and lazily retrieves pages of records as you iterate over the collection. You can also page manually using the `page` method.
795
-
796
- For more information about these methods, view the [auto-generated library docs](https://www.twilio.com/docs/libraries/reference/twilio-node/).
797
- ```
798
-
799
- ```
800
- ### Enable Debug Logging
801
-
802
- There are two ways to enable debug logging in the default HTTP client. You can create an environment variable called `TWILIO_LOG_LEVEL` and set it to `debug` or you can set the logLevel variable on the client as debug:
803
-
804
- ```javascript
805
- const accountSid = process.env.TWILIO_ACCOUNT_SID;
806
- const authToken = process.env.TWILIO_AUTH_TOKEN;
807
-
808
- const client = require('twilio')(accountSid, authToken, {
809
- logLevel: 'debug',
810
- });
811
- ```
812
-
813
- You can also set the logLevel variable on the client after constructing the Twilio client:
814
-
815
- ```javascript
816
- const client = require('twilio')(accountSid, authToken);
817
- client.logLevel = 'debug';
818
- ```
819
- ```
820
-
821
- ```
822
- const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
823
- const authToken = 'your_auth_token';
824
-
825
- const client = require('twilio')(accountSid, authToken);
826
-
827
- client.messages
828
- .create({
829
- to: '+14158675309',
830
- from: '+14258675310',
831
- body: 'Ahoy!',
832
- })
833
- .then(() => {
834
- // Access details about the last request
835
- console.log(client.lastRequest.method);
836
- console.log(client.lastRequest.url);
837
- console.log(client.lastRequest.auth);
838
- console.log(client.lastRequest.params);
839
- console.log(client.lastRequest.headers);
840
- console.log(client.lastRequest.data);
841
-
842
- // Access details about the last response
843
- console.log(client.httpClient.lastResponse.statusCode);
844
- console.log(client.httpClient.lastResponse.body);
845
- });
846
- ```
847
- ```
848
-
849
- ```
850
- If the Twilio API returns a 400 or a 500 level HTTP response, `twilio-node` will throw an error including relevant information, which you can then `catch`:
851
-
852
- ```js
853
- client.messages
854
- .create({
855
- body: 'Hello from Node',
856
- to: '+12345678901',
857
- from: '+12345678901',
858
- })
859
- .then((message) => console.log(message))
860
- .catch((error) => {
861
- // You can implement your fallback code here
862
- console.log(error);
863
- });
864
- ```
865
- ```
866
-
867
- ```
868
- ## Contributing
869
-
870
- Bug fixes, docs, and library improvements are always welcome. Please refer to our [Contributing Guide](CONTRIBUTING.md) for detailed information on how you can contribute.
871
-
872
- > Please be aware that a large share of the files are auto-generated by our backend tool. You are welcome to suggest changes and submit PRs illustrating the changes. However, we'll have to make the changes in the underlying tool. You can find more info about this in the [Contributing Guide](CONTRIBUTING.md).
873
- ```
874
-
875
- ```typescript
876
- /** The recipient\'s phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (for SMS/MMS) or [channel address](https://www.twilio.com/docs/messaging/channels), e.g. `whatsapp:+15552229999`. */
877
- to: string;
878
- ```
879
-
880
- ```typescript
881
- /** The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service\'s Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. */
882
- messagingServiceSid?: string;
883
- ```
884
-
885
- ```typescript
886
- /** The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. */
887
- mediaUrl?: Array<string>;
888
- ```
889
-
890
- ```typescript
891
- export interface CallListInstanceCreateOptions {
892
- /** The phone number, SIP address, or client identifier to call. */
893
- to: string;
894
- /** The phone number or client identifier to use as the caller id. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `From` must also be a phone number. */
895
- from: string;
896
- ```
897
-
898
- ```typescript
899
- /** TwiML instructions for the call Twilio will use without fetching Twiml from url parameter. If both `twiml` and `url` are provided then `twiml` parameter will be ignored. Max 4000 characters. */
900
- twiml?: TwiML | string;
901
- ```
902
-
903
- ```typescript
904
- class VoiceResponse extends TwiML {
905
- /**
906
- * <Response> TwiML for Voice
907
- */
908
- constructor() {
909
- super();
910
- this._propertyName = "response";
911
- }
912
- ```
913
-
914
- ```typescript
915
- connect(attributes?: VoiceResponse.ConnectAttributes): VoiceResponse.Connect {
916
- return new VoiceResponse.Connect(this.response.ele("Connect", attributes));
917
- ```
918
-
919
- ```typescript
920
- export type MessagingResponse = IMessagingResponse;
921
- export const MessagingResponse = IMessagingResponse;
922
- ```
923
-
924
- ```typescript
925
- export type validateBody = typeof webhooks.validateBody;
926
- export const validateBody = webhooks.validateBody;
927
- export type validateRequest = typeof webhooks.validateRequest;
928
- export const validateRequest = webhooks.validateRequest;
929
- export type validateRequestWithBody = typeof webhooks.validateRequestWithBody;
930
- export const validateRequestWithBody = webhooks.validateRequestWithBody;
931
- export type validateExpressRequest = typeof webhooks.validateExpressRequest;
932
- export const validateExpressRequest = webhooks.validateExpressRequest;
933
- export type validateIncomingRequest = typeof webhooks.validateIncomingRequest;
934
- export const validateIncomingRequest = webhooks.validateIncomingRequest;
935
- ```
936
-
937
- ```typescript
938
- export interface Request {
939
- protocol: string;
940
- header(name: string): string | undefined;
941
- headers: IncomingHttpHeaders;
942
- originalUrl: string;
943
- rawBody?: any;
944
- body: any;
945
- }
946
- ```