Twilio — Complete Guide (from scratch → advanced)
Everything you need to test & integrate Twilio SMS/OTP in your Node.js app, including trial usage, test credentials, DLT and Alphanumeric Sender ID for India — by .
1. What is Twilio?
Twilio is a cloud communications platform (APIs + services) that lets developers send SMS, voice calls, WhatsApp messages, emails (via SendGrid), video, and more — programmatically. Use it to send OTPs, transactional alerts, marketing messages, and build chat/voice/video features.
2. Main Services Twilio Provides
- Programmable SMS — send/receive SMS & MMS worldwide.
- Voice — make/receive calls, build IVR and conferencing.
- WhatsApp API — send templated WhatsApp messages.
- Verify — managed OTP service (handles generation, expiry, rate limits).
- SendGrid Email — transactional & marketing email delivery.
- Video & Chat — SDKs for real-time communication.
3. Free Trial vs Paid Account — Limitations & Benefits
Twilio gives a trial credit (approx. $15.50) to sign up and test. There are key restrictions while on trial:
- Messages can only be sent to **verified phone numbers** (you must verify recipient numbers in Twilio Console).
- Messages show a prefix: "Sent from your Twilio trial account".
- You must use a Twilio-owned phone number as the
fromnumber (you can claim/buy one using trial credits).
Once you upgrade (add billing), you can send to any number, buy short codes or alphanumeric sender IDs, and remove the trial prefix.
4. Quick Start — Get a Twilio Number (step-by-step)
- Create account at twilio.com/try-twilio and verify email & phone.
- Go to Phone Numbers → Manage → Active numbers. If empty, click Buy a number (use trial credit).
- Copy the Twilio number (example:
+14155238886) — this will be yourTWILIO_PHONE_NUMBERin `.env`. - Verify your destination phone (Console → Verified Caller IDs) to receive trial messages.
5. Node.js Example (CommonJS) — Send OTP via SMS
Install packages:
npm install express twilio dotenv
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_PHONE_NUMBER=+14155238886
PORT=5000
require('dotenv').config();
const express = require('express');
const twilio = require('twilio');
const app = express();
app.use(express.json());
const client = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
app.post('/api/send-otp', async (req, res) => {
const { phone } = req.body; // +919xxxxxxxxx
if (!phone) return res.status(400).json({ success:false, message:'phone required' });
const otp = Math.floor(100000 + Math.random() * 900000);
try {
const message = await client.messages.create({
body: `Your OTP is ${otp}`,
from: process.env.TWILIO_PHONE_NUMBER,
to: phone
});
return res.json({ success:true, sid: message.sid, otp }); // remove otp in prod
} catch (err) {
console.error(err);
return res.status(500).json({ success:false, error: err.message });
}
});
app.listen(process.env.PORT || 5000, () => console.log('Server running'));
Test with Postman:
POST http://localhost:5000/api/send-otp
Headers: { "Content-Type": "application/json" }
Body: { "phone": "+919xxxxxxxxx" }
6. Twilio Test Credentials & Magic Numbers (simulate)
If you want to test without sending real SMS, use Twilio Test Credentials (found in Console > Project Settings). These return simulated responses — useful for unit tests.
// Use Test SID & Token (do not send real SMS)
const client = twilio(process.env.TWILIO_TEST_SID, process.env.TWILIO_TEST_AUTH_TOKEN);
// Use magic 'from' and 'to' numbers from Twilio docs to simulate success/failure.
See Twilio docs: Test Credentials & Magic Numbers
7. Twilio Verify — Managed OTP (recommended for production)
Verify is a Twilio service that generates OTPs, tracks attempts, expiry, and verification — reduces your implementation work and helps with compliance.
const verifyServiceSid = 'VAXXXXXXXXXXXXXXXXXXXXXX'; // create Verify Service in console
// create verification
await client.verify.services(verifyServiceSid)
.verifications.create({ to: phone, channel: 'sms' });
// check verification (user-provided code)
await client.verify.services(verifyServiceSid)
.verificationChecks.create({ to: phone, code: userInputCode });
Twilio Verify also supports channel: 'sms', 'call', and
'whatsapp'.
8. Alphanumeric Sender ID (show company name instead of number)
To display a company name (like ZNINFOTECH) instead of a number, you
need an Alphanumeric Sender ID. Important points:
- Supported in many countries including India (but not US/Canada).
- You must upgrade your Twilio account (trial accounts cannot register alphanumeric senders).
- For India, you also need DLT registration and template approval (explained below).
Register at Twilio Console → Messaging → Alphanumeric Sender IDs and follow the registration flow for each destination country.
9. DLT (India) — Mandatory for SMS & templates
DLT is the telecom-mandated system in India to prevent spam. For Indian SMS delivery using an alphanumeric header you must:
- Register your Entity on a DLT operator portal (e.g. Jio, Airtel, VI, BSNL).
- Create & approve a Header (sender name) — e.g.
ZNINFOTECH. - Create & approve Templates with variables like
{#var#}for OTPs. - Map your SMS provider (MSG91/Twilio) as a telemarketer in DLT portal.
- Link DLT Template ID and Header in Twilio or your SMS provider dashboard.
10. Postman Examples
Send OTP (simple):
POST http://localhost:5000/api/send-otp
Headers: Content-Type: application/json
Body:
{ "phone": "+919xxxxxxxxx" }
Verify (if using your own verify logic):
POST http://localhost:5000/api/verify-otp
Body: { "phone": "+919xxxxxxxxx", "otp": "123456" }
11. Common Errors & Troubleshooting
| Error | Meaning / Fix |
|---|---|
'From' +919... is not a Twilio phone number |
Use a Twilio-owned number in from (buy one from console). |
Trial messages show prefix |
Upgrade account to remove the trial prefix. |
| Messages appear "sent" but not delivered (India) | Check DLT template/header approval and route type (transactional vs promotional). |
| Alphanumeric sender not showing | Register sender in Twilio & DLT (for India), and ensure destination country supports alpha senders. |
12. Security & Best Practices
- Never return OTP in production responses or log them in plaintext.
- Use HTTPS and store Twilio credentials in environment variables (never commit `.env`).
- Rate-limit OTP requests (prevent abuse) and implement resend cooldowns.
- Use Twilio Verify in production to reduce compliance & security handling.
- For India, complete DLT registration before production rollout.
13. Alternatives to Twilio
- MSG91 — India-focused, cheaper for local traffic (needs DLT).
- Firebase Authentication — free for small volumes, great for learning phone auth (needs frontend integration).
- Textbelt — simple API with limited free usage (region-dependent).
- Plivo, Nexmo (Vonage) — other global SMS providers with similar APIs.