twilio
Multi-channel communications APIs and services
$ npx docs2skills add twilio-communicationsTwilio Communications
Multi-channel communications APIs and services for SMS, voice, video, email, and WhatsApp messaging.
What this skill does
Twilio provides programmable communication APIs that enable developers to embed messaging, voice calling, video, and email capabilities into applications. It handles the complex infrastructure for global telecommunications, offering reliable delivery across SMS, WhatsApp, voice calls, video conferences, and email through a unified REST API.
Developers use Twilio to build customer engagement platforms, two-factor authentication systems, contact centers, notification services, and communication workflows without managing telecom infrastructure. It provides phone number provisioning, carrier relationships, fraud prevention, and compliance tools across 180+ countries.
Prerequisites
- Twilio account with Account SID and Auth Token
- Phone number verification for production usage
- Helper library for your programming language
- Webhook endpoint for receiving events (optional)
- SSL certificate for webhook URLs in production
Quick start
npm install twilio
const twilio = require('twilio');
const client = twilio('ACCOUNT_SID', 'AUTH_TOKEN');
// Send SMS
client.messages
.create({
body: 'Hello from Twilio!',
from: '+15017122661',
to: '+15558675310'
})
.then(message => console.log(message.sid));
// Make voice call
client.calls
.create({
twiml: '<Response><Say>Hello World</Say></Response>',
to: '+15558675310',
from: '+15017122661'
})
.then(call => console.log(call.sid));
Core concepts
REST API: All Twilio services use HTTP REST endpoints with JSON responses. Authentication via HTTP Basic Auth with Account SID as username and Auth Token as password.
TwiML: Twilio Markup Language - XML instructions that tell Twilio how to handle calls and messages. Used for voice call flows, SMS responses, and chat routing.
Webhooks: HTTP callbacks Twilio sends to your application when events occur (message received, call ended, etc.). Must respond within 15 seconds or Twilio retries.
SIDs: Unique identifiers for all Twilio resources (Account, Message, Call, etc.). Always 34 characters starting with resource prefix (AC for Account, SM for Message).
Subaccounts: Isolated Twilio accounts under your master account for organizing projects, billing, or customer separation.
Key API surface
// Messaging
client.messages.create({body, from, to, mediaUrl?, statusCallback?})
client.messages.list({from?, to?, dateSent?})
client.messages(sid).fetch()
// Voice calls
client.calls.create({to, from, twiml?, url?, timeout?})
client.calls(sid).update({status: 'completed'}) // hang up
client.calls.list({status?, startTime?})
// Phone numbers
client.incomingPhoneNumbers.create({phoneNumber, voiceUrl?, smsUrl?})
client.availablePhoneNumbers('US').local.list({contains?, areaCode?})
// Verification (2FA)
client.verify.services(sid).verifications.create({to, channel: 'sms'})
client.verify.services(sid).verificationChecks.create({to, code})
// Video rooms
client.video.rooms.create({uniqueName, type: 'group'})
client.tokens.create({identity, grants: [videoGrant]})
Common patterns
Two-factor authentication:
// Start verification
const verification = await client.verify
.services('VA123...')
.verifications
.create({to: '+15558675310', channel: 'sms'});
// Check code
const check = await client.verify
.services('VA123...')
.verificationChecks
.create({to: '+15558675310', code: '123456'});
if (check.status === 'approved') {
// User verified
}
Interactive voice response (IVR):
app.post('/voice', (req, res) => {
const twiml = new VoiceResponse();
const gather = twiml.gather({
input: 'speech dtmf',
timeout: 3,
action: '/gather'
});
gather.say('Press 1 for sales, 2 for support');
res.type('text/xml');
res.send(twiml.toString());
});
WhatsApp messaging:
const message = await client.messages.create({
from: 'whatsapp:+14155238886',
body: 'Your order has shipped!',
to: 'whatsapp:+15551234567'
});
Conference calling:
// Add participants to conference
client.calls.create({
to: '+15558675310',
from: '+15017122661',
twiml: '<Response><Dial><Conference>MyConference</Conference></Dial></Response>'
});
Webhook handler with signature validation:
const twilio = require('twilio');
app.post('/sms-webhook', (req, res) => {
const signature = req.headers['x-twilio-signature'];
const valid = twilio.validateRequest(
'AUTH_TOKEN',
signature,
'https://yourapp.com/sms-webhook',
req.body
);
if (!valid) return res.status(403).send('Forbidden');
console.log(`Received: ${req.body.Body} from ${req.body.From}`);
res.status(200).send();
});
Configuration
Environment variables:
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_PHONE_NUMBER=+15551234567
Client initialization options:
const client = twilio(accountSid, authToken, {
region: 'sydney', // Geographic region
edge: 'dublin', // Edge location
timeout: 30000 // Request timeout
});
Webhook configuration:
- SMS webhook URL:
https://yourapp.com/sms - Voice webhook URL:
https://yourapp.com/voice - Status callback URL:
https://yourapp.com/status - Must use HTTPS in production
- Must respond with HTTP 200 within 15 seconds
Best practices
- Always validate webhook signatures to prevent spoofing attacks
- Use status callbacks to track message delivery and call completion
- Implement exponential backoff for rate limit handling (20,000 requests/hour default)
- Store message and call SIDs for debugging and customer service
- Use subaccounts to isolate different applications or customers
- Set appropriate timeouts for voice calls to avoid hanging connections
- Use E.164 format for all phone numbers (+1234567890)
- Implement idempotency keys for critical operations to prevent duplicates
- Use TwiML bins for static responses to reduce server load
- Monitor usage and set billing alerts to control costs
Gotchas and common mistakes
Phone number formatting: Must use E.164 format (+1234567890). Missing + or country code causes failures.
Webhook timeouts: Twilio expects 200 response within 15 seconds. Long-running operations will cause retries and duplicate processing.
TwiML case sensitivity: XML tags are case-sensitive. <say> fails, must be <Say>.
Rate limits: 1 message/second per phone number. Burst sending requires multiple numbers or Messaging Service.
Webhook validation: Production apps must validate X-Twilio-Signature header. Twilio provides validation functions in helper libraries.
Media URLs: MMS media URLs expire after ~4 hours. Download and store media if needed long-term.
Geographic permissions: International SMS/voice requires geographic permissions enabled in console.
Alphanumeric sender IDs: Only work for one-way SMS, not supported in US/Canada, require registration in many countries.
Call recording: Requires legal compliance warnings in many jurisdictions. Check local laws.
Message delivery: SMS delivery not guaranteed. Use status callbacks and Verify API for critical communications.
Concurrent modification: Race conditions possible when multiple requests modify same resource simultaneously.
Free trial limitations: Trial accounts have verified number restrictions and Twilio branding on calls.
Short codes: Require separate provisioning process, take weeks to approve, have different rate limits than long codes.