1 | # twilio-node
|
2 |
|
3 | [![][test-workflow-image]][test-workflow-url]
|
4 | [![][npm-version-image]][npm-url]
|
5 | [![][npm-install-size-image]][npm-install-size-url]
|
6 | [![][npm-downloads-image]][npm-downloads-url]
|
7 |
|
8 | ## Documentation
|
9 |
|
10 | The documentation for the Twilio API can be found [here][apidocs].
|
11 |
|
12 | The Node library documentation can be found [here][libdocs].
|
13 |
|
14 | ## Versions
|
15 |
|
16 | `twilio-node` uses a modified version of [Semantic Versioning](https://semver.org) for all changes. [See this document](VERSIONS.md) for details.
|
17 |
|
18 | ### Supported Node.js Versions
|
19 |
|
20 | This library supports the following Node.js implementations:
|
21 |
|
22 | - Node.js 14
|
23 | - Node.js 16
|
24 | - Node.js 18
|
25 |
|
26 | TypeScript is supported for TypeScript version 2.9 and above.
|
27 |
|
28 | > **Warning**
|
29 | > 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.
|
30 |
|
31 | ## Installation
|
32 |
|
33 | `npm install twilio` or `yarn add twilio`
|
34 |
|
35 | ### Test your installation
|
36 |
|
37 | To make sure the installation was successful, try sending yourself an SMS message, like this:
|
38 |
|
39 | ```js
|
40 | // Your AccountSID and Auth Token from console.twilio.com
|
41 | const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
|
42 | const authToken = 'your_auth_token';
|
43 |
|
44 | const client = require('twilio')(accountSid, authToken);
|
45 |
|
46 | client.messages
|
47 | .create({
|
48 | body: 'Hello from twilio-node',
|
49 | to: '+12345678901', // Text your number
|
50 | from: '+12345678901', // From a valid Twilio number
|
51 | })
|
52 | .then((message) => console.log(message.sid));
|
53 | ```
|
54 |
|
55 | After a brief delay, you will receive the text message on your phone.
|
56 |
|
57 | > **Warning**
|
58 | > 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.
|
59 |
|
60 | ## Usage
|
61 |
|
62 | Check out these [code examples](examples) in JavaScript and TypeScript to get up and running quickly.
|
63 |
|
64 | ### Environment Variables
|
65 |
|
66 | `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`.
|
67 |
|
68 | If your environment requires SSL decryption, you can set the path to CA bundle in the env var `TWILIO_CA_BUNDLE`.
|
69 |
|
70 | ### Client Initialization
|
71 |
|
72 | 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:
|
73 |
|
74 | ```javascript
|
75 | // Your Account SID, Subaccount SID Auth Token from console.twilio.com
|
76 | const accountSid = process.env.TWILIO_ACCOUNT_SID;
|
77 | const authToken = process.env.TWILIO_AUTH_TOKEN;
|
78 | const subaccountSid = process.env.TWILIO_ACCOUNT_SUBACCOUNT_SID;
|
79 |
|
80 | const client = require('twilio')(accountSid, authToken);
|
81 | const mainAccountCalls = client.api.v2010.account.calls.list; // SID not specified, so defaults to accountSid
|
82 | const subaccountCalls = client.api.v2010.account(subaccountSid).calls.list; // SID specified as subaccountSid
|
83 | ```
|
84 |
|
85 | ### Lazy Loading
|
86 |
|
87 | `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`:
|
88 |
|
89 | ```javascript
|
90 | // Your Account SID and Auth Token from console.twilio.com
|
91 | const accountSid = process.env.TWILIO_ACCOUNT_SID;
|
92 | const authToken = process.env.TWILIO_AUTH_TOKEN;
|
93 |
|
94 | const client = require('twilio')(accountSid, authToken, {
|
95 | lazyLoading: false,
|
96 | });
|
97 | ```
|
98 |
|
99 | ### Enable Auto-Retry with Exponential Backoff
|
100 |
|
101 | `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`.
|
102 |
|
103 | 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`.
|
104 |
|
105 | ```javascript
|
106 | const accountSid = process.env.TWILIO_ACCOUNT_SID;
|
107 | const authToken = process.env.TWILIO_AUTH_TOKEN;
|
108 |
|
109 | const client = require('twilio')(accountSid, authToken, {
|
110 | autoRetry: true,
|
111 | maxRetries: 3,
|
112 | });
|
113 | ```
|
114 |
|
115 | ### Specify Region and/or Edge
|
116 |
|
117 | 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:
|
118 |
|
119 | ```javascript
|
120 | const accountSid = process.env.TWILIO_ACCOUNT_SID;
|
121 | const authToken = process.env.TWILIO_AUTH_TOKEN;
|
122 |
|
123 | const client = require('twilio')(accountSid, authToken, {
|
124 | region: 'au1',
|
125 | edge: 'sydney',
|
126 | });
|
127 | ```
|
128 |
|
129 | Alternatively, specify the edge and/or region after constructing the Twilio client:
|
130 |
|
131 | ```javascript
|
132 | const client = require('twilio')(accountSid, authToken);
|
133 | client.region = 'au1';
|
134 | client.edge = 'sydney';
|
135 | ```
|
136 |
|
137 | This will result in the `hostname` transforming from `api.twilio.com` to `api.sydney.au1.twilio.com`.
|
138 |
|
139 | ### Iterate through records
|
140 |
|
141 | 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.
|
142 |
|
143 | `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.
|
144 |
|
145 | For more information about these methods, view the [auto-generated library docs](https://www.twilio.com/docs/libraries/reference/twilio-node/).
|
146 |
|
147 | ```js
|
148 | // Your Account SID and Auth Token from console.twilio.com
|
149 | const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
|
150 | const authToken = 'your_auth_token';
|
151 | const client = require('twilio')(accountSid, authToken);
|
152 |
|
153 | client.calls.each((call) => console.log(call.direction));
|
154 | ```
|
155 |
|
156 | ### Enable Debug Logging
|
157 |
|
158 | 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:
|
159 |
|
160 | ```javascript
|
161 | const accountSid = process.env.TWILIO_ACCOUNT_SID;
|
162 | const authToken = process.env.TWILIO_AUTH_TOKEN;
|
163 |
|
164 | const client = require('twilio')(accountSid, authToken, {
|
165 | logLevel: 'debug',
|
166 | });
|
167 | ```
|
168 |
|
169 | You can also set the logLevel variable on the client after constructing the Twilio client:
|
170 |
|
171 | ```javascript
|
172 | const client = require('twilio')(accountSid, authToken);
|
173 | client.logLevel = 'debug';
|
174 | ```
|
175 |
|
176 | ### Debug API requests
|
177 |
|
178 | 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.
|
179 |
|
180 | For example, you can retrieve the status code of the last response like so:
|
181 |
|
182 | ```js
|
183 | const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
|
184 | const authToken = 'your_auth_token';
|
185 |
|
186 | const client = require('twilio')(accountSid, authToken);
|
187 |
|
188 | client.messages
|
189 | .create({
|
190 | to: '+14158675309',
|
191 | from: '+14258675310',
|
192 | body: 'Ahoy!',
|
193 | })
|
194 | .then(() => {
|
195 | // Access details about the last request
|
196 | console.log(client.lastRequest.method);
|
197 | console.log(client.lastRequest.url);
|
198 | console.log(client.lastRequest.auth);
|
199 | console.log(client.lastRequest.params);
|
200 | console.log(client.lastRequest.headers);
|
201 | console.log(client.lastRequest.data);
|
202 |
|
203 | // Access details about the last response
|
204 | console.log(client.httpClient.lastResponse.statusCode);
|
205 | console.log(client.httpClient.lastResponse.body);
|
206 | });
|
207 | ```
|
208 |
|
209 | ### Handle exceptions
|
210 |
|
211 | 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`:
|
212 |
|
213 | ```js
|
214 | client.messages
|
215 | .create({
|
216 | body: 'Hello from Node',
|
217 | to: '+12345678901',
|
218 | from: '+12345678901',
|
219 | })
|
220 | .then((message) => console.log(message))
|
221 | .catch((error) => {
|
222 | // You can implement your fallback code here
|
223 | console.log(error);
|
224 | });
|
225 | ```
|
226 |
|
227 | or with `async/await`:
|
228 |
|
229 | ```js
|
230 | try {
|
231 | const message = await client.messages.create({
|
232 | body: 'Hello from Node',
|
233 | to: '+12345678901',
|
234 | from: '+12345678901',
|
235 | });
|
236 | console.log(message);
|
237 | } catch (error) {
|
238 | // You can implement your fallback code here
|
239 | console.error(error);
|
240 | }
|
241 | ```
|
242 |
|
243 | If you are using callbacks, error information will be included in the `error` parameter of the callback.
|
244 |
|
245 | 400-level errors are [normal during API operation](https://www.twilio.com/docs/api/rest/request#get-responses) ("Invalid number", "Cannot deliver SMS to that number", for example) and should be handled appropriately.
|
246 |
|
247 | ### Use a custom HTTP Client
|
248 |
|
249 | To use a custom HTTP client with this helper library, please see the [advanced example of how to do so](./advanced-examples/custom-http-client.md).
|
250 |
|
251 | ### Use webhook validation
|
252 |
|
253 | See [example](examples/express.js) for a code sample for incoming Twilio request validation.
|
254 |
|
255 | ## Docker image
|
256 |
|
257 | The `Dockerfile` present in this repository and its respective `twilio/twilio-node` Docker image are currently used by Twilio for testing purposes only.
|
258 |
|
259 | ## Getting help
|
260 |
|
261 | If you need help installing or using the library, please check the [Twilio Support Help Center](https://support.twilio.com) first, and [file a support ticket](https://twilio.com/help/contact) if you don't find an answer to your question.
|
262 |
|
263 | 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!
|
264 |
|
265 | ## Contributing
|
266 |
|
267 | 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.
|
268 |
|
269 | > ⚠️ 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).
|
270 |
|
271 | If you're not familiar with the GitHub pull request/contribution process, [this is a nice tutorial](https://gun.io/blog/how-to-github-fork-branch-and-pull-request/).
|
272 |
|
273 | ### Get started
|
274 |
|
275 | If you want to familiarize yourself with the project, you can start by [forking the repository](https://help.github.com/articles/fork-a-repo/) and [cloning it in your local development environment](https://help.github.com/articles/cloning-a-repository/). The project requires [Node.js](https://nodejs.org) to be installed on your machine.
|
276 |
|
277 | After cloning the repository, install the dependencies by running the following command in the directory of your cloned repository:
|
278 |
|
279 | ```bash
|
280 | npm install
|
281 | ```
|
282 |
|
283 | You can run the existing tests to see if everything is okay by executing:
|
284 |
|
285 | ```bash
|
286 | npm test
|
287 | ```
|
288 |
|
289 | 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:
|
290 |
|
291 | ```bash
|
292 | npm run test:javascript -- -m .\*client.\*
|
293 | ```
|
294 |
|
295 | [apidocs]: https://www.twilio.com/docs/api
|
296 | [libdocs]: https://twilio.github.io/twilio-node
|
297 |
|
298 | [test-workflow-image]: https://github.com/twilio/twilio-node/actions/workflows/test-and-deploy.yml/badge.svg
|
299 | [test-workflow-url]: https://github.com/twilio/twilio-node/actions/workflows/test-and-deploy.yml
|
300 | [npm-downloads-image]: https://img.shields.io/npm/dm/twilio.svg
|
301 | [npm-downloads-url]: https://npmcharts.com/compare/twilio?minimal=true
|
302 | [npm-install-size-image]: https://badgen.net/packagephobia/install/twilio
|
303 | [npm-install-size-url]: https://packagephobia.com/result?p=twilio
|
304 | [npm-url]: https://npmjs.org/package/twilio
|
305 | [npm-version-image]: https://img.shields.io/npm/v/twilio.svg
|