twilio-node

repository·main·Indexed 23 days ago

https://github.com/twilio/twilio-node

The official Node.js helper library for the Twilio API, enabling programmatic interaction with services such as SMS and Voice. It supports Node.js 20, 22, and 24 (lts), as well as TypeScript 2.9+. Key features include OAuth 2.0 Client Credentials Flow, automatic pagination via list() and each(), custom HTTP client support, and built-in handling for RestException.

Tokens
15.2K
Snippets
14
Records
105
Agent score
79%

What's inside twilio-node

  1. Understand the twilio-node versioning strategy

    main

    The twilio-node library follows a modified Semantic Versioning (MAJOR.MINOR.PATCH) model. To prevent breaking changes from being introduced automatically during updates, it is strongly recommended to pin your dependency to at least a specific major version, and ideally a specific minor version.

    • PATCH (MAJOR.MINOR.PATCH): Incremented for backwards-compatible bug fixes. These are generally safe to upgrade.
    • MINOR (MAJOR.MINOR.PATCH): Incremented when new features are added or small, backwards-incompatible changes (like function signature changes) are introduced. Upgrading may require manual code adjustments.
    • MAJOR (MAJOR.MINOR.PATCH): Incremented for large-scale breaking changes that require extensive code reworking. These are communicated in advance via Release Candidates.
  2. Use custom HTTP clients for testing and mocking

    main

    Injecting a custom httpClient allows you to intercept the request pipeline. This is useful for:

    • Mocking API responses: Implement a client that returns predefined data instead of making real network calls. This enables fast, reliable unit and integration testing without needing a connection to Twilio.
    • Custom Authorization: Adding specific headers required by upstream proxy servers.
    • Custom Headers: Injecting specialized metadata into every outgoing request.
  3. Initialize the Twilio Client

    main

    You can initialize the Twilio client using CommonJS or ESM. If you do not specify an account SID for V2010 operations, the client defaults to the TWILIO_ACCOUNT_SID used during initialization. This allows you to easily switch between a main account and subaccounts by specifying the subaccount SID in the method call.

    // Your Account SID, Subaccount SID Auth Token from console.twilio.com
    const accountSid = process.env.TWILIO_ACCOUNT_SID;
    const authToken = process.env.TWILIO_AUTH_TOKEN;
    const subaccountSid = process.env.TWILIO_ACCOUNT_SUBACCOUNT_SID;
    
    const client = require('twilio')(accountSid, authToken);
    const mainAccountCalls = client.api.v2010.account.calls.list; // SID not specified, so defaults to accountSid
    const subaccountCalls = client.api.v2010.account(subaccountSid).calls.list; // SID specified as subaccountSid
  4. Migrate from 3.x.x to 4.x.x

    main

    Upgrading from version 3.x.x to 4.x.x introduces several breaking changes regarding Node.js support, lazy loading, type definitions, Access Tokens, TwiML functions, and TaskRouter operations.

    Node.js Support

    • Upgrade to Node.js >= 14.
    • Support for Node.js < 14 has been dropped.

    Lazy Loading

    • Lazy loading is now enabled by default for required Twilio modules.

    Type Changes

    • Certain response properties now use the Record type with string keys. This includes the subresourceUris property for v2010 APIs and the links properties for non-v2010 APIs.

    Access Tokens

    • Creating an AccessToken now requires an identity in the options object.
    • ConversationsGrant is deprecated in favor of VoiceGrant.
    • IpMessagingGrant has been removed.

    TwiML Function Renames

    Several TwiML methods have been renamed to remove the ssml prefix or simplify names:

    • Refer.referSip() $\rightarrow$ Refer.sip()
    • Say.ssmlBreak() and Say.break_() $\rightarrow$ Say.break()
    • Say.ssmlEmphasis() $\rightarrow$ Say.emphasis()
    • Say.ssmlLang() $\rightarrow$ Say.lang()
    • Say.ssmlP() $\rightarrow$ Say.p()
    • Say.ssmlPhoneme() $\rightarrow$ Say.phoneme()
    • Say.ssmlProsody() $\rightarrow$ Say.prosody()
    • Say.ssmlS() $\rightarrow$ Say.s()
    • Say.ssmlSayAs() $\rightarrow$ Say.sayAs()
    • Say.ssmlSub() $\rightarrow$ Say.sub()
    • Say.ssmlW() $\rightarrow$ Say.w()

    Example (Say):

    // Old
    const response = new VoiceResponse();
    const say = response.say("Hello");
    say.ssmlEmphasis("you");
    
    // New
    const response = new VoiceResponse();
    const say = response.say("Hello");
    say.emphasis("you");

    TaskRouter Workers Statistics

    Cumulative and Real-Time Workers Statistics no longer accept a WorkerSid in the path. The API structure has changed from a method call on a specific worker to a property access on the workers collection.

    Example (Cumulative Statistics):

    // Old
    client.taskrouter.v1.workspaces('WS...').workers('WK...).cumulativeStatistics()
    
    // New
    client.taskrouter.v1.workspaces('WS...').workers.cumulativeStatistics()

    Example (Real-Time Statistics):

    // Old
    client.taskrouter.v1.workspaces('WS...').workers('WK...).realTimeStatistics()
    
    // New
    client.taskrouter.v1.workspaces('WS...').workers.realTimeStatistics()
  5. Handle API exceptions with RestException

    main

    When the Twilio API returns a 400 or 500 level HTTP response, the library throws an error. For precise error handling, you can check if the error is an instance of RestException to access specific Twilio error details.

    RestException properties:

    • code: The Twilio error code.
    • message: The error message.
    • status: The HTTP status code.
    • moreInfo: A URL providing more information about the error.
    // ESM/ES6
    import twilio from 'twilio';
    const { RestException } = twilio;
    
    // CommonJS
    const { RestException } = require('twilio');
    
    // Usage
    try {
      const message = await client.messages.create({
        body: 'Hello from Node',
        to: '+12345678901',
        from: '+12345678901',
      });
    } catch (error) {
      if (error instanceof RestException) {
        console.log(`Twilio Error ${error.code}: ${error.message}`);
        console.log(`Status: ${error.status}`);
        console.log(`More info: ${error.moreInfo}`);
      } else {
        console.error('Other error:', error);
      }
    }
  6. Use a custom HTTP Client with the Twilio Node Helper Library

    main

    By default, the Twilio Node.js Helper Library uses a RequestClient powered by axios to make requests to Twilio servers. If you need to modify HTTP requests (e.g., for custom timeouts, proxy support, or adding custom headers), you can provide your own implementation of a RequestClient by passing it to the httpClient option during client initialization.

    To use a custom client, pass an instance of your class to the third argument of the twilio initialization function.

    const twilio = require('twilio');
    const MyRequestClient = require('./MyRequestClient');
    
    const accountSid = process.env.ACCOUNT_SID;
    const authToken = process.env.AUTH_TOKEN;
    
    const client = twilio(accountSid, authToken, {
      // Custom HTTP Client instance
      httpClient: new MyRequestClient(60000),
    });
  7. Specify Twilio Region and Edge

    main

    To utilize Twilio's Global Infrastructure, you can specify a region and/or edge. This transforms the hostname from api.twilio.com to api.{edge}.{region}.twilio.com.

    // Option 1: During instantiation
    const client = require('twilio')(accountSid, authToken, {
      region: 'au1',
      edge: 'sydney',
    });
    
    // Option 2: After construction
    const client = require('twilio')(accountSid, authToken);
    client.region = 'au1';
    client.edge = 'sydney';
  8. Upgrade to twilio 6.x.x

    main

    When upgrading to version 6.x.x of the twilio library, you must ensure your environment meets the new minimum Node.js requirement.

    Breaking Changes:

    • Minimum Node.js version raised to 20: Support for Node.js versions below 20 has been dropped. You must upgrade to Node.js >= 20 before updating the twilio package to 6.x.x.
  9. Enable Debug Logging

    main

    You can enable debug logging for the default HTTP client in two ways:

    1. Set the TWILIO_LOG_LEVEL environment variable to debug.
    2. Set the logLevel property on the client instance to 'debug'.

    You can set this during instantiation or after the client has been constructed.

    // During instantiation
    const client = require('twilio')(accountSid, authToken, {
      logLevel: 'debug',
    });
    
    // After construction
    const client = require('twilio')(accountSid, authToken);
    client.logLevel = 'debug';
  10. Configure a proxy for Twilio requests

    main

    There are two ways to route Twilio requests through a proxy server:

    1. Using Environment Variables

    The library natively supports the HTTP_PROXY environment variable. It uses the https-proxy-agent package to handle the connection. Set the variable in your environment or .env file:

    HTTP_PROXY=http://127.0.0.1:8888

    2. Using a Custom HTTP Client

    If you are using a custom RequestClient (e.g., based on axios), you can pass proxy configuration directly to your client's constructor and include it in the axios options object. Axios expects a proxy object with protocol, host, and port.

    // Pass proxy settings to client constructor
    const client = twilio(accountSid, authToken, {
      httpClient: new MyRequestClient(60000, {
          protocol: 'https',
          host: '127.0.0.1',
          port: 9000,
        }
      ),
    });
    
    // Inside your MyRequestClient implementation:
    class MyRequestClient {
      constructor(timeout, proxy){
        this.timeout = timeout;
        this.proxy = proxy;
      }
    
      request(opts) {
        const options = {
          proxy: this.proxy,
          // ... other axios options
        };
        // ...
      }
    }