OAuth 2.0 authentication with Client Credentials Flow
mainThe library supports Client Credentials Flow-based OAuth 2.0 authentication for Twilio APIs.
For implementation details, refer to the following examples in the repository:
repository·main·Indexed 23 days ago
https://github.com/twilio/twilio-nodeThe 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.
The library supports Client Credentials Flow-based OAuth 2.0 authentication for Twilio APIs.
For implementation details, refer to the following examples in the repository:
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.
MAJOR.MINOR.PATCH): Incremented for backwards-compatible bug fixes. These are generally safe to upgrade.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.MINOR.PATCH): Incremented for large-scale breaking changes that require extensive code reworking. These are communicated in advance via Release Candidates.Injecting a custom httpClient allows you to intercept the request pipeline. This is useful for:
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 subaccountSidUpgrading 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.
Record type with string keys. This includes the subresourceUris property for v2010 APIs and the links properties for non-v2010 APIs.AccessToken now requires an identity in the options object.ConversationsGrant is deprecated in favor of VoiceGrant.IpMessagingGrant has been removed.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");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()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);
}
}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),
});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';You can install the Twilio Node library using npm or yarn:
npm install twilioor
yarn add twilioWhen upgrading to version 6.x.x of the twilio library, you must ensure your environment meets the new minimum Node.js requirement.
Breaking Changes:
twilio package to 6.x.x.You can enable debug logging for the default HTTP client in two ways:
TWILIO_LOG_LEVEL environment variable to debug.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';There are two ways to route Twilio requests through a proxy server:
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:8888If 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
};
// ...
}
}