A comprehensive Node.js SDK for the Twilio communications platform, enabling SMS, voice, video, and other communication services integration.
—
TwiML (Twilio Markup Language) builders provide a fluent, type-safe interface for creating XML responses to handle incoming calls, messages, and faxes. These response builders generate valid TwiML that instructs Twilio how to handle communications.
TwiML response builder for handling voice calls with comprehensive support for call control, media playback, recording, and advanced telephony features.
/**
* TwiML response builder for voice communications
* Generates XML instructions for handling incoming voice calls
*/
class VoiceResponse {
constructor();
/** Generate the final TwiML XML string */
toString(): string;
/** Add XML comments to the response */
comment(comment: string): XMLElement;
commentBefore(comment: string): XMLElement;
commentAfter(comment: string): XMLElement;
}Usage Examples:
import TwilioSDK from "twilio";
// Access TwiML classes via namespace
const { twiml } = TwilioSDK;
// Basic voice response
const response = new twiml.VoiceResponse();
response.say("Hello, welcome to our service!");
response.hangup();
console.log(response.toString());
// Outputs: <?xml version="1.0" encoding="UTF-8"?><Response><Say>Hello, welcome to our service!</Say><Hangup/></Response>Core TwiML verbs for voice communication and call control.
/** Text-to-speech with voice and language options */
say(message?: string, attributes?: SayAttributes): Say;
/** Play audio files or streams */
play(url?: string, attributes?: PlayAttributes): Play;
/** Collect DTMF input from caller */
gather(attributes?: GatherAttributes): Gather;
/** Make outbound calls or connect to other parties */
dial(number?: string, attributes?: DialAttributes): Dial;
/** Record audio from the caller */
record(attributes?: RecordAttributes): Record;
/** Redirect call to another TwiML URL */
redirect(url?: string, attributes?: RedirectAttributes): Redirect;
/** Pause execution for specified duration */
pause(attributes?: PauseAttributes): Pause;
/** Terminate the call */
hangup(): Hangup;
/** Reject incoming call with specific reason */
reject(attributes?: RejectAttributes): Reject;Advanced TwiML verbs for complex call flows and integrations.
/** Connect call to WebRTC clients, conferences, or other services */
connect(attributes?: ConnectAttributes): Connect;
/** Place caller in a queue for agent handling */
enqueue(name?: string, attributes?: EnqueueAttributes): Enqueue;
/** Leave current queue or conference */
leave(): Leave;
/** Process payments during the call */
pay(attributes?: PayAttributes): Pay;
/** Prompt for caller input with customizable settings */
prompt(attributes?: PromptAttributes): Prompt;
/** Refer call to another party (SIP REFER) */
refer(attributes?: ReferAttributes): Refer;
/** Send SMS during voice call */
sms(message?: string, attributes?: SmsAttributes): Sms;
/** Start call recording or stream */
start(attributes?: StartAttributes): Start;
/** Stop call recording or stream */
stop(): Stop;
/** Echo call audio back to caller */
echo(): Echo;
/** Add caller to named queue */
queue(name: string, attributes?: QueueAttributes): Queue;interface SayAttributes {
/** Voice to use for speech synthesis */
voice?: "man" | "woman" | "alice" | "Polly.Aditi" | "Polly.Amy" | string;
/** Language and accent for speech */
language?: "en" | "en-au" | "en-ca" | "en-gb" | "en-in" | "en-us" | string;
/** Number of times to repeat the message */
loop?: number;
}
interface PlayAttributes {
/** Number of times to play the audio */
loop?: number;
/** Digits to press to skip playback */
digits?: string;
}
interface GatherAttributes {
/** URL to POST collected digits */
action?: string;
/** HTTP method for action URL */
method?: "GET" | "POST";
/** Timeout in seconds for input collection */
timeout?: number;
/** Key to finish input collection */
finishOnKey?: string;
/** Maximum number of digits to collect */
numDigits?: number;
/** Minimum number of digits to collect */
minDigits?: number;
/** Maximum number of attempts */
maxAttempts?: number;
/** Text to speak while gathering input */
input?: "dtmf" | "speech" | "dtmf speech";
/** Language for speech recognition */
language?: string;
/** Hints for speech recognition */
hints?: string;
/** Profanity filter for speech */
profanityFilter?: boolean;
}
interface DialAttributes {
/** Caller ID to display */
callerId?: string;
/** Timeout in seconds */
timeout?: number;
/** Music to play while connecting */
hangupOnStar?: boolean;
/** Timeout music URL */
timeLimit?: number;
/** URL for call status updates */
action?: string;
/** HTTP method for action URL */
method?: "GET" | "POST";
/** Record the call */
record?: "do-not-record" | "record-from-answer" | "record-from-ringing";
/** Trim silence from recordings */
trim?: "trim-silence" | "do-not-trim";
/** Recording status callback URL */
recordingStatusCallback?: string;
/** Recording status callback method */
recordingStatusCallbackMethod?: "GET" | "POST";
}
interface RecordAttributes {
/** URL to POST recording details */
action?: string;
/** HTTP method for action URL */
method?: "GET" | "POST";
/** Maximum recording length in seconds */
timeout?: number;
/** Key to finish recording */
finishOnKey?: string;
/** Maximum recording duration */
maxLength?: number;
/** Play beep before recording */
playBeep?: boolean;
/** Trim silence from recording */
trim?: "trim-silence" | "do-not-trim";
/** Recording status callback URL */
recordingStatusCallback?: string;
/** Transcribe the recording */
transcribe?: boolean;
/** Transcription callback URL */
transcribeCallback?: string;
}
interface QueueAttributes {
/** URL to request when call leaves queue */
url?: string;
/** HTTP method for queue URL */
method?: "GET" | "POST";
/** Number of seconds to wait in queue before giving up */
reservationSid?: string;
/** Post task receipt to this URL when enqueued */
postWorkActivitySid?: string;
}Usage Examples:
// Interactive Voice Response (IVR) system
const response = new twiml.VoiceResponse();
const gather = response.gather({
action: "/handle-selection",
numDigits: 1,
timeout: 10
});
gather.say("Press 1 for sales, 2 for support, or 0 for operator");
response.say("No input received. Goodbye!");
response.hangup();
// Call forwarding with recording
const response = new twiml.VoiceResponse();
response.say("This call will be recorded for quality purposes");
const dial = response.dial({
callerId: "+1234567890",
record: "record-from-answer",
action: "/call-complete"
});
dial.number("+0987654321");
// Conference call setup
const response = new twiml.VoiceResponse();
response.say("Welcome to the conference");
const dial = response.dial();
const conference = dial.conference("support-room", {
startConferenceOnEnter: true,
endConferenceOnExit: false,
waitUrl: "http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient"
});TwiML response builder for handling SMS and MMS messages.
/**
* TwiML response builder for messaging communications
* Generates XML instructions for handling incoming messages
*/
class MessagingResponse {
constructor();
/** Generate the final TwiML XML string */
toString(): string;
/** Add XML comments to the response */
comment(comment: string): XMLElement;
commentBefore(comment: string): XMLElement;
commentAfter(comment: string): XMLElement;
}TwiML verbs for message handling and response generation.
/** Send reply message with text and optional media */
message(body?: string, attributes?: MessageAttributes): Message;
/** Redirect to another TwiML URL for further processing */
redirect(url?: string, attributes?: RedirectAttributes): Redirect;interface MessageAttributes {
/** Callback URL for message status updates */
action?: string;
/** Phone number to send message from */
from?: string;
/** HTTP method for action URL */
method?: "GET" | "POST";
/** Phone number to send message to */
to?: string;
/** Status callback URL */
statusCallback?: string;
}
interface RedirectAttributes {
/** HTTP method for redirect */
method?: "GET" | "POST";
}Usage Examples:
// Auto-reply with message
const response = new twiml.MessagingResponse();
response.message("Thanks for your message! We'll get back to you soon.");
// Forward message with media
const response = new twiml.MessagingResponse();
const message = response.message("Here's your requested information:");
message.media("https://example.com/document.pdf");
// Conditional response based on message content
const response = new twiml.MessagingResponse();
if (incomingMessage.includes("STOP")) {
response.message("You've been unsubscribed from notifications.");
} else if (incomingMessage.includes("HELP")) {
response.redirect("/help-menu");
} else {
response.message("Message received. Reply HELP for options or STOP to unsubscribe.");
}TwiML response builder for handling incoming fax transmissions.
/**
* TwiML response builder for fax communications
* Generates XML instructions for handling incoming faxes
*/
class FaxResponse {
constructor();
/** Generate the final TwiML XML string */
toString(): string;
/** Add XML comments to the response */
comment(comment: string): XMLElement;
commentBefore(comment: string): XMLElement;
commentAfter(comment: string): XMLElement;
}TwiML verb for fax reception and processing.
/** Configure fax reception settings */
receive(attributes?: ReceiveAttributes): Receive;interface ReceiveAttributes {
/** URL to POST fax reception status */
action?: string;
/** Media type for storing received fax */
mediaType?: "application/pdf" | "image/tiff";
/** HTTP method for action URL */
method?: "GET" | "POST";
/** Page size for fax interpretation */
pageSize?: "letter" | "legal" | "a4";
/** Whether to store fax media */
storeMedia?: boolean;
}Usage Examples:
// Basic fax reception
const response = new twiml.FaxResponse();
response.receive({
action: "/fax-received",
mediaType: "application/pdf",
storeMedia: true
});
// Fax with custom page size and processing
const response = new twiml.FaxResponse();
response.receive({
action: "/process-fax",
method: "POST",
pageSize: "legal",
mediaType: "image/tiff",
storeMedia: true
});VoiceResponse includes comprehensive support for Speech Synthesis Markup Language (SSML) elements for enhanced speech control.
// SSML elements for advanced speech synthesis
class SsmlBreak {
constructor(attributes?: { strength?: string; time?: string });
}
class SsmlEmphasis {
constructor(attributes?: { level?: "strong" | "moderate" | "reduced" });
}
class SsmlLang {
constructor(attributes?: { xmlLang?: string });
}
class SsmlPhoneme {
constructor(attributes?: { alphabet?: string; ph?: string });
}
class SsmlProsody {
constructor(attributes?: {
pitch?: string;
rate?: string;
volume?: string;
});
}
class SsmlSayAs {
constructor(attributes?: {
interpretAs?: "characters" | "spell-out" | "cardinal" | "number" | "ordinal" | "digits" | "fraction" | "unit" | "date" | "time" | "telephone" | "address";
format?: string;
});
}
class SsmlSub {
constructor(attributes?: { alias?: string });
}
class SsmlP {
constructor(attributes?: object);
}
class SsmlS {
constructor(attributes?: object);
}
class SsmlW {
constructor(attributes?: object);
}Usage Examples:
// Using SSML for enhanced speech synthesis
const response = new twiml.VoiceResponse();
const say = response.say();
say.ssmlBreak({ strength: "medium" });
say.ssmlEmphasis({ level: "strong" }, "Important announcement:");
say.ssmlProsody({ rate: "slow" }, "Please listen carefully");
say.ssmlSayAs({ interpretAs: "telephone" }, "415-555-1212");interface XMLElement {
ele(name: string, attributes?: object, text?: string): XMLElement;
comment(comment: string): XMLElement;
commentBefore(comment: string): XMLElement;
commentAfter(comment: string): XMLElement;
}
abstract class TwiML {
protected _propertyName: string;
protected response: XMLElement;
/** Generate the final XML string representation */
toString(): string;
}Install with Tessl CLI
npx tessl i tessl/npm-twilio