Sending SMS on JavaScript (Node.js): twilio library
In modern web development, it is often necessary to send SMS notifications to users: registration confirmation, two-factor authentication codes, order status alerts, and much more. In the Node.js ecosystem, one of the most popular and reliable libraries for this task is twilio. This is the official SDK from Twilio, which provides a simple and powerful API for programmatically sending SMS, voice calls, and working with other telecommunication services.
In this article, we will thoroughly cover how to install, configure, and use the twilio library to send SMS from your Node.js application. You will learn the main methods, how to handle errors, and see several practical examples.
Installation and Configuration
To get started, you will need an account on Twilio. After registration, you will receive:
- Account SID — a unique identifier for your account.
- Auth Token — a secret key for authenticating requests.
- Twilio phone number — the phone number from which SMS will be sent (provided free for testing).
Install the library via npm:
npm install twilioAfter installation, create a file send-sms.js and include the library, passing your credentials:
const twilio = require('twilio');
const accountSid = 'YOUR_ACCOUNT_SID';const authToken = 'YOUR_AUTH_TOKEN';const client = twilio(accountSid, authToken);Basic SMS Sending
To send a message, use the client.messages.create() method. It accepts an object with three required fields:
body— the text of the message (up to 1600 characters for a single SMS).from— your Twilio number (in the format+1234567890).to— the recipient's number (also in international format).
Example of sending a simple SMS:
client.messages .create({ body: 'Hello! This is a test message from Twilio.', from: '+1234567890', to: '+79876543210' }) .then(message => console.log('Message sent. SID:', message.sid)) .catch(error => console.error('Error:', error));After successful sending, you will receive a message object containing a unique sid (message identifier), delivery status, and other information.
Asynchronous Sending with async/await
For a more modern approach, use the async/await syntax. Wrap the call in a try...catch block for error handling:
const sendSMS = async (to, body) => { try { const message = await client.messages.create({ body: body, from: '+1234567890', to: to }); console.log(`SMS sent to ${to}. SID: ${message.sid}`); return message; } catch (error) { console.error('Failed to send SMS:', error.message); throw error; }};
// UsagesendSMS('+79876543210', 'Your confirmation code: 1234');Additional Parameters
The library supports many optional parameters. Here are some of them:
mediaUrl— URL of an image or other media file (for MMS).statusCallback— URL for receiving delivery status notifications (webhook).applicationSid— Twilio application SID for additional configuration.
Example of sending an MMS with an image:
client.messages .create({ from: '+1234567890', to: '+79876543210', body: 'Check out this ph Also in library
Cryptography in C++: Encryption and Hashing with OpenSSL and Crypto++
Internationalization (i18n) in PHP: gettext library and modern approaches
gomock for Go: Complete Guide with Examples
Task Queues for Swift: Complete Guide to GCD and Operation Queues