Menu

The Twilio Node Helper Library

The twilio-node helper library lets you write Node.js code to make HTTP requests to the Twilio API.

This library is open-source, so if you find a feature missing or a bug, we encourage you to file an issue or contribute back to the twilio-node project.

Server-Side only, not Front-End

This library is intended for back-end applications running on Node.js. If you are building a front-end, client-side application with React, Angular, Vue, Svelte, or plain HTML/CSS/Javascript, then your application client should only use one of the Twilio JavaScript SDKs below.

  • JavaScript SDKs

    Twilio's JavaScript SDKs are used in the browser to create video conversations, make VoIP phone calls, or implement real-time omnichannel chat. Get started with the SDK you need.

  • 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.

    For general HTTP requests to the Twilio API, consider writing a Twilio Function and making an HTTP request to the Function from within your app's client-side code.

    If you want to see how to put this Node.js library together with the Twilio Client Javascript library for voice, check out the Browser Dialer with Node.js and Vue.js. You'll see how to secure your Twilio account credentials from your end-users. The example creates capability tokens with a Node.js endpoint. Not using Vue? That guide also has example code for React, Angular, and Ember, if you prefer any of those frameworks.

    Installation

    Prerequisites

    Prior to installation, make sure that you are running a compatible version of Node.js. You can verify your version by running the following in your command line:

    node --version
    

    twilio-node supports the following versions:

    • Node.js 14
    • Node.js 16
    • Node.js 18

    If you are running on Node.js 12 or older and cannot upgrade, you can install version 3.x of twilio-node instead.

    Install

    The primary way to install twilio-node is from NPM. You can run the command below from your project directory to install the library:

    npm install twilio
    

    Then, import the library in your code:

    const twilio = require('twilio');
    

    Test your installation

    To make sure the installation was successful, try sending yourself an SMS message, like this:

    const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; // Your Account SID from www.twilio.com/console
    const authToken = 'your_auth_token'; // Your Auth Token from www.twilio.com/console
    
    const client = require('twilio')(accountSid, authToken);
    
    client.messages
      .create({
        body: 'Hello from twilio-node',
        to: '+12345678901', // Text this number
        from: '+12345678901', // From a valid Twilio number
      })
      .then((message) => console.log(message.sid));
    

    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.

    Using this library

    Authenticate Client

    // Your Account SID and Auth Token from console.twilio.com
    const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
    const authToken = 'your_auth_token';
    const client = require('twilio')(accountSid, authToken);
    

    Create a new record

    // Your Account SID and Auth Token from console.twilio.com
    const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
    const authToken = 'your_auth_token';
    const client = require('twilio')(accountSid, authToken);
    
    client.calls
      .create({
        url: 'http://demo.twilio.com/docs/voice.xml',
        to: '+14155551212',
        from: '+15017250604',
      })
      .then(call => console.log(call.sid));
    

    Get an existing record

    // Your Account SID and Auth Token from console.twilio.com
    const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
    const authToken = 'your_auth_token';
    const client = require('twilio')(accountSid, authToken);
    
    client
      .calls('CA42ed11f93dc08b952027ffbc406d0868')
      .fetch()
      .then(call => console.log(call.to));
    

    Iterate through records

    // Your Account SID and Auth Token from console.twilio.com
    const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
    const authToken = 'your_auth_token';
    const client = require('twilio')(accountSid, authToken);
    
    client.calls.each(call => console.log(call.direction));
    

    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.

    Lazy Loading

    twilio-node supports lazy loading required modules for faster loading time. Lazy loading is enabled by default. To disable lazy loading, instantiate the Twilio client with the lazyLoading flag set to false:

    // Your Account SID and Auth Token from console.twilio.com
    const accountSid = process.env.TWILIO_ACCOUNT_SID;
    const authToken = process.env.TWILIO_AUTH_TOKEN;
    
    const client = require('twilio')(accountSid, authToken, {
      lazyLoading: false
    });
    

    Enable Auto-Retry with Exponential Backoff

    Auto-retry is a way to try and ensure that a request completes successfully when presented with intermittent errors from Twilio's API. 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.

    // Your Account SID and Auth Token from console.twilio.com
    const accountSid = process.env.TWILIO_ACCOUNT_SID;
    const authToken = process.env.TWILIO_AUTH_TOKEN;
    
    const client = require('twilio')(accountSid, authToken, {
      autoRetry: true,
      maxRetries: 3
    });
    

    Specify Region and/or Edge

    To take advantage of Twilio's Global Infrastructure, specify the target Region and/or Edge for the client:

    // Your Account SID and Auth Token from console.twilio.com
    const accountSid = process.env.TWILIO_ACCOUNT_SID;
    const authToken = process.env.TWILIO_AUTH_TOKEN;
    
    const client = require('twilio')(accountSid, authToken, {
      region: 'au1',
      edge: 'sydney',
    });
    

    Alternatively, specify the edge and/or region after constructing the Twilio client:

    const client = require('twilio')(accountSid, authToken);
    client.region = 'au1';
    client.edge = 'sydney';
    

    This will result in the hostname transforming from api.twilio.com to api.sydney.au1.twilio.com.

    Handle exceptions

    If the Twilio API returns a 400 or a 500 level HTTP response, the twilio-node library will throw an error including relevant information, which you can then catch:

    client.messages
      .create({
        body: 'Hello from Node',
        to: '+12345678901',
        from: '+12345678901',
      })
      .then((message) => console.log(message))
      .catch((error) => {
        // You can implement your fallback code here
        console.log(error);
      });
    

    or with async/await:

    try {
      const message = await client.messages.create({
        body: 'Hello from Node',
        to: '+12345678901',
        from: '+12345678901',
      });
      console.log(message);
    } catch (error) {
      // You can implement your fallback code here
      console.error(error);
    }
    

    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.

    Debug API requests

    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:

    // Your Account SID and Auth Token from console.twilio.com
    const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
    const authToken = 'your_auth_token';
    
    // require the Twilio module and create a REST client
    const client = require('twilio')(accountSid, authToken);
    
    client.messages
      .create({
        to: '+14158675309',
        from: '+14258675310',
        body: 'Ahoy!',
      })
      .then(() => {
        // Access details about the last request
        console.log(client.lastRequest.method);
        console.log(client.lastRequest.url);
        console.log(client.lastRequest.auth);
        console.log(client.lastRequest.params);
        console.log(client.lastRequest.headers);
        console.log(client.lastRequest.data);
    
        // Access details about the last response
        console.log(client.httpClient.lastResponse.statusCode);
        console.log(client.httpClient.lastResponse.body);
      });
    

    More documentation

    Once you're up and running with the Node helper library, you'll find code samples using the latest version in our REST API docs and in the documentation for every Twilio product. You can also find auto-generated library docs for the latest SDK here.

    Access version 3.x of the SDK

    The older 3.x version of the SDK will continue to work and is available to download, but is no longer supported. Refer to the upgrade guide to check for any breaking changes between 3.x and 4.x.

    Should you need to install this version from NPM, you can do so with the following command.

    npm install twilio@3.84.1
    

    Alternately, you can view this version of the SDK on GitHub and download it directly from there.

    Rate this page:

    Need some help?

    We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Stack Overflow Collective or browsing the Twilio tag on Stack Overflow.

    Thank you for your feedback!

    Please select the reason(s) for your feedback. The additional information you provide helps us improve our documentation:

    Sending your feedback...
    🎉 Thank you for your feedback!
    Something went wrong. Please try again.

    Thanks for your feedback!

    thanks-feedback-gif