Gathering detailed insights and metrics for twilio
Gathering detailed insights and metrics for twilio
Gathering detailed insights and metrics for twilio
Gathering detailed insights and metrics for twilio
npm install twilio
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
1,410 Stars
1,367 Commits
513 Forks
89 Watching
9 Branches
132 Contributors
Updated on 28 Nov 2024
TypeScript (98.83%)
JavaScript (1.15%)
Makefile (0.01%)
Cumulative downloads
Total Downloads
Last day
-1.1%
268,444
Compared to previous day
Last week
6.4%
1,432,276
Compared to previous week
Last month
11.5%
5,681,353
Compared to previous month
Last year
14.6%
60,747,710
Compared to previous year
The documentation for the Twilio API can be found here.
The Node library documentation can be found here.
twilio-node
uses a modified version of Semantic Versioning for all changes. See this document for details.
This library supports the following Node.js implementations:
TypeScript is supported for TypeScript version 2.9 and above.
Warning 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.
npm install twilio
or yarn add twilio
To make sure the installation was successful, try sending yourself an SMS message, like this:
1// Your AccountSID and Auth Token from console.twilio.com 2const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; 3const authToken = 'your_auth_token'; 4 5const client = require('twilio')(accountSid, authToken); 6 7client.messages 8 .create({ 9 body: 'Hello from twilio-node', 10 to: '+12345678901', // Text your number 11 from: '+12345678901', // From a valid Twilio number 12 }) 13 .then((message) => console.log(message.sid));
After a brief delay, you will receive the text message on your phone.
Warning 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 for more information.
Check out these code examples in JavaScript and TypeScript to get up and running quickly.
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
.
If your environment requires SSL decryption, you can set the path to CA bundle in the env var TWILIO_CA_BUNDLE
.
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:
1// Your Account SID, Subaccount SID Auth Token from console.twilio.com 2const accountSid = process.env.TWILIO_ACCOUNT_SID; 3const authToken = process.env.TWILIO_AUTH_TOKEN; 4const subaccountSid = process.env.TWILIO_ACCOUNT_SUBACCOUNT_SID; 5 6const client = require('twilio')(accountSid, authToken); 7const mainAccountCalls = client.api.v2010.account.calls.list; // SID not specified, so defaults to accountSid 8const subaccountCalls = client.api.v2010.account(subaccountSid).calls.list; // SID specified as subaccountSid
twilio-node
supports lazy loading required modules for faster loading time. Lazy loading is enabled by default. To disable lazy loading, simply instantiate the Twilio client with the lazyLoading
flag set to false
:
1// Your Account SID and Auth Token from console.twilio.com 2const accountSid = process.env.TWILIO_ACCOUNT_SID; 3const authToken = process.env.TWILIO_AUTH_TOKEN; 4 5const client = require('twilio')(accountSid, authToken, { 6 lazyLoading: false, 7});
twilio-node
supports automatic retry with exponential backoff when API requests receive an Error 429 response. 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
.
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
.
1const accountSid = process.env.TWILIO_ACCOUNT_SID; 2const authToken = process.env.TWILIO_AUTH_TOKEN; 3 4const client = require('twilio')(accountSid, authToken, { 5 autoRetry: true, 6 maxRetries: 3, 7});
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
.
Optionally, the socket timeout and maximum number of sockets can also be set. See the example below:
1const accountSid = process.env.TWILIO_ACCOUNT_SID; 2const authToken = process.env.TWILIO_AUTH_TOKEN; 3 4const client = require('twilio')(accountSid, authToken, { 5 timeout: 30000, // HTTPS agent's socket timeout in milliseconds, default is 30000 6 keepAlive: true, // https.Agent keepAlive option, default is false 7 keepAliveMsecs: 1000, // https.Agent keepAliveMsecs option in milliseconds, default is 1000 8 maxSockets: 20, // https.Agent maxSockets option, default is 20 9 maxTotalSockets: 100, // https.Agent maxTotalSockets option, default is 100 10 maxFreeSockets: 5, // https.Agent maxFreeSockets option, default is 5 11 scheduling: "lifo", // https.Agent scheduling option, default is 'lifo' 12});
To take advantage of Twilio's Global Infrastructure, specify the target Region and/or Edge for the client:
1const accountSid = process.env.TWILIO_ACCOUNT_SID; 2const authToken = process.env.TWILIO_AUTH_TOKEN; 3 4const client = require('twilio')(accountSid, authToken, { 5 region: 'au1', 6 edge: 'sydney', 7});
Alternatively, specify the edge and/or region after constructing the Twilio client:
1const client = require('twilio')(accountSid, authToken); 2client.region = 'au1'; 3client.edge = 'sydney';
This will result in the hostname
transforming from api.twilio.com
to api.sydney.au1.twilio.com
.
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.
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.
For more information about these methods, view the auto-generated library docs.
1// Your Account SID and Auth Token from console.twilio.com 2const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; 3const authToken = 'your_auth_token'; 4const client = require('twilio')(accountSid, authToken); 5 6client.calls.each((call) => console.log(call.direction));
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:
1const accountSid = process.env.TWILIO_ACCOUNT_SID; 2const authToken = process.env.TWILIO_AUTH_TOKEN; 3 4const client = require('twilio')(accountSid, authToken, { 5 logLevel: 'debug', 6});
You can also set the logLevel variable on the client after constructing the Twilio client:
1const client = require('twilio')(accountSid, authToken); 2client.logLevel = 'debug';
To assist with debugging, the library allows you to access the underlying request and response objects. This capability is built into the default HTTP client that ships with the library.
For example, you can retrieve the status code of the last response like so:
1const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; 2const authToken = 'your_auth_token'; 3 4const client = require('twilio')(accountSid, authToken); 5 6client.messages 7 .create({ 8 to: '+14158675309', 9 from: '+14258675310', 10 body: 'Ahoy!', 11 }) 12 .then(() => { 13 // Access details about the last request 14 console.log(client.lastRequest.method); 15 console.log(client.lastRequest.url); 16 console.log(client.lastRequest.auth); 17 console.log(client.lastRequest.params); 18 console.log(client.lastRequest.headers); 19 console.log(client.lastRequest.data); 20 21 // Access details about the last response 22 console.log(client.httpClient.lastResponse.statusCode); 23 console.log(client.httpClient.lastResponse.body); 24 });
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
:
1client.messages 2 .create({ 3 body: 'Hello from Node', 4 to: '+12345678901', 5 from: '+12345678901', 6 }) 7 .then((message) => console.log(message)) 8 .catch((error) => { 9 // You can implement your fallback code here 10 console.log(error); 11 });
or with async/await
:
1try { 2 const message = await client.messages.create({ 3 body: 'Hello from Node', 4 to: '+12345678901', 5 from: '+12345678901', 6 }); 7 console.log(message); 8} catch (error) { 9 // You can implement your fallback code here 10 console.error(error); 11}
If you are using callbacks, error information will be included in the error
parameter of the callback.
400-level errors are normal during API operation ("Invalid number", "Cannot deliver SMS to that number", for example) and should be handled appropriately.
To use a custom HTTP client with this helper library, please see the advanced example of how to do so.
See example for a code sample for incoming Twilio request validation.
The Dockerfile
present in this repository and its respective twilio/twilio-node
Docker image are currently used by Twilio for testing purposes only.
If you need help installing or using the library, please check the Twilio Support Help Center first, and file a support ticket if you don't find an answer to your question.
If you've instead found a bug in the library or would like new features added, go ahead and open issues or pull requests against this repo!
Bug fixes, docs, and library improvements are always welcome. Please refer to our Contributing Guide for detailed information on how you can contribute.
⚠️ 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.
If you're not familiar with the GitHub pull request/contribution process, this is a nice tutorial.
If you want to familiarize yourself with the project, you can start by forking the repository and cloning it in your local development environment. The project requires Node.js to be installed on your machine.
After cloning the repository, install the dependencies by running the following command in the directory of your cloned repository:
1npm install
You can run the existing tests to see if everything is okay by executing:
1npm test
To run just one specific test file instead of the whole suite, provide a JavaScript regular expression that will match your spec file's name, like:
1npm run test:javascript -- -m .\*client.\*
No vulnerabilities found.
Reason
20 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
0 existing vulnerabilities detected
Reason
packaging workflow detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 7
Details
Reason
Found 6/29 approved changesets -- score normalized to 2
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
project is not fuzzed
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More