A comprehensive Node.js SDK for the Twilio communications platform, enabling SMS, voice, video, and other communication services integration.
npx @tessl/cli install tessl/npm-twilio@5.9.0The Twilio Node.js SDK is a comprehensive library that provides a complete interface to the Twilio communications platform. It enables developers to integrate SMS, voice, video, chat, and other communication services into their Node.js applications with full TypeScript support and modern async/await patterns.
npm install twilioimport TwilioSDK from "twilio";
// Create client with auto-discovery of credentials
const client = TwilioSDK(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
// Access individual components via namespace properties
const {
Twilio,
jwt,
twiml,
validateRequest,
webhook,
ClientCredentialProviderBuilder,
OrgsCredentialProviderBuilder,
NoAuthCredentialProvider,
RestException,
RequestClient
} = TwilioSDK;
// Access nested components
const { AccessToken, ClientCapability, ValidationToken } = jwt;
const { VoiceResponse, MessagingResponse, FaxResponse } = twiml;
const { TaskRouterCapability, util } = jwt.taskrouter;For CommonJS:
const TwilioSDK = require("twilio");
const client = TwilioSDK(accountSid, authToken);
// Access components the same way
const { jwt, twiml, validateRequest } = TwilioSDK;import TwilioSDK from "twilio";
// Initialize the Twilio client
const client = TwilioSDK(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_AUTH_TOKEN
);
// Send an SMS message
const message = await client.messages.create({
body: "Hello from Twilio!",
from: "+1234567890",
to: "+0987654321"
});
// Make a voice call
const call = await client.calls.create({
url: "http://demo.twilio.com/docs/voice.xml",
from: "+1234567890",
to: "+0987654321"
});
// Generate TwiML response
const { twiml } = TwilioSDK;
const response = new twiml.VoiceResponse();
response.say("Hello World");
console.log(response.toString());The Twilio SDK is organized around several key architectural components:
Twilio class provides access to 38+ service domains through a unified interfaceThe core REST client providing access to all Twilio services including messaging, voice, video, and platform services. Supports automatic authentication, request retries, and comprehensive error handling.
function TwilioSDK(
accountSid?: string,
authToken?: string,
opts?: ClientOpts
): Twilio;
interface ClientOpts {
httpClient?: RequestClient;
accountSid?: string;
env?: NodeJS.ProcessEnv;
edge?: string;
region?: string;
lazyLoading?: boolean;
logLevel?: string;
userAgentExtensions?: string[];
autoRetry?: boolean;
maxRetryDelay?: number;
maxRetries?: number;
timeout?: number;
keepAlive?: boolean;
}TwiML (Twilio Markup Language) builders for creating XML responses to handle incoming calls, messages, and faxes. Provides a fluent, type-safe interface for constructing complex call flows and messaging logic.
class VoiceResponse {
constructor();
say(message?: string, attributes?: SayAttributes): Say;
play(url?: string, attributes?: PlayAttributes): Play;
gather(attributes?: GatherAttributes): Gather;
dial(number?: string, attributes?: DialAttributes): Dial;
record(attributes?: RecordAttributes): Record;
redirect(url?: string, attributes?: RedirectAttributes): Redirect;
pause(attributes?: PauseAttributes): Pause;
hangup(): Hangup;
reject(attributes?: RejectAttributes): Reject;
}
class MessagingResponse {
constructor();
message(body?: string, attributes?: MessageAttributes): Message;
redirect(url?: string, attributes?: RedirectAttributes): Redirect;
}JWT token generation and validation for Twilio Client applications, TaskRouter workers, and service capabilities. Supports access tokens, client capabilities, and request validation.
class AccessToken {
constructor(accountSid: string, keySid: string, secret: string, options?: AccessTokenOptions);
addGrant(grant: Grant): AccessToken;
toJwt(algorithm?: string): string;
}
class ClientCapability {
constructor(options: ClientCapabilityOptions);
addScope(scope: Scope): ClientCapability;
toJwt(): string;
}Security utilities for validating incoming Twilio webhook requests to ensure they originate from Twilio servers. Includes signature validation and Express.js middleware support.
function validateRequest(
authToken: string,
twilioSignature: string,
url: string,
params: object
): boolean;
function validateRequestWithBody(
authToken: string,
twilioSignature: string,
url: string,
body: string
): boolean;
function webhook(options?: WebhookOptions): (req: any, res: any, next: Function) => void;Advanced authentication strategies for OAuth2, organizational accounts, and custom credential management. Enables flexible authentication patterns beyond basic username/password.
class ClientCredentialProviderBuilder {
setClientId(clientId: string): ClientCredentialProviderBuilder;
setClientSecret(clientSecret: string): ClientCredentialProviderBuilder;
setTokenManager(tokenManager: TokenManager): ClientCredentialProviderBuilder;
build(): ClientCredentialProvider;
}
class NoAuthCredentialProvider {
constructor();
toAuthStrategy(): AuthStrategy;
}Core utilities for HTTP request handling and error management used throughout the SDK.
class RestException extends Error {
status: number;
code: number;
moreInfo: string;
detail: string;
constructor(response: any);
}
class RequestClient {
constructor(options?: RequestClientOptions);
request<T>(opts: RequestOpts): Promise<T>;
}
interface RequestClientOptions {
timeout?: number;
keepAlive?: boolean;
keepAliveMsecs?: number;
maxSockets?: number;
maxTotalSockets?: number;
maxFreeSockets?: number;
ca?: string | Buffer;
}interface ClientOpts {
httpClient?: RequestClient;
accountSid?: string;
env?: NodeJS.ProcessEnv;
edge?: string;
region?: string;
lazyLoading?: boolean;
logLevel?: string;
userAgentExtensions?: string[];
autoRetry?: boolean;
maxRetryDelay?: number;
maxRetries?: number;
validationClient?: ValidationClientOptions;
timeout?: number;
keepAlive?: boolean;
keepAliveMsecs?: number;
maxSockets?: number;
maxTotalSockets?: number;
maxFreeSockets?: number;
scheduling?: "fifo" | "lifo" | undefined;
ca?: string | Buffer;
}
interface RequestOpts {
method?: HttpMethod;
uri?: string;
username?: string;
password?: string;
authStrategy?: AuthStrategy;
headers?: Headers;
params?: object;
data?: object;
timeout?: number;
allowRedirects?: boolean;
logLevel?: string;
}
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "PATCH";
interface Headers {
[key: string]: string;
}