DEV Community

Dallington Asingwire
Dallington Asingwire

Posted on • Updated on

How to send sms to a phone number in node.js

Twilio is a platform used by hundreds of thousands of businesses and more than ten million developers worldwide to build unique and personalized experiences for their customers. Twilio is popular for being a gateway to send text, voice, chat, video and email through API.

So today, we shall look at how to send a text message to the user through Twilio using Node.js.
First we need to install Twilio helper library by running the following command;

 npm i twilio
Enter fullscreen mode Exit fullscreen mode

Code (TwilioMessagingService.js)

var twilio = require('twilio');
require('dotenv').config();
const accountSid = process.env.accountSid; //Your Account SID from twilio console
const authToken = process.env.authToken; //Your Auth Token from twilio console

var client = new twilio(accountSid, authToken);

module.exports = {
    sendSms: async(req, callback) => {
        const phoneNumber = req.to; // phone number must start with country code
        client.messages.create({
            body: req.message,
            to: phoneNumber, //'',  // Text this number
            from: '+xxxxxxxxxx' // From a valid Twilio number
        }, function(err, message) {
            if (err) {
                callback(err.message);
            } else {
                callback(null, message.sid);
            }
        });
    },

}



Enter fullscreen mode Exit fullscreen mode

In the above code example, first step is to access Twilio module for use using require function through this line of code var twilio = require('twilio').

Next step is to instantiate Twilio client by using new twilio(accountSid, authToken) and its constructor takes in accountSid and authToken which are obtained from your Twilio console. Both accountSID and authToken are configured in .env file and I read those values using dotenv npm library. Once you have created an account with Twilio, you can access Twilio console and get those credentials.

You can use this link https://www.twilio.com/blog/better-twilio-authentication-csharp-twilio-api-keys to see how to get AccountSID and AuthToken.

In module.exports instruction, I have a method named sendSms() which is used to send text message to a user phone number. Through an Twilio instance client, you can send a message using messages.create() function which takes in one parameter, a json object with keys body (the message to be sent to the user), to (a phone number that belongs to the user, receiving the message) and from (the phone number of the sender).

The function sendSms takes in 2 parameters i.e req which contains the message body and the phone number to which text message is sent, and a callback function.

Calling sendSms
You can call sendSms forexample using the code snippet below;

const Twilio = require("../helpers/TwilioMessagingService");

const sendTextMessage = (phoneNumber) => {

 Twilio.sendSms({ to: phoneNumber, message: `Hey, this text message 
        has been sent through Twilio platform` }, (err,smsData) => {
        console.log(err, smsData);
   });

}

Enter fullscreen mode Exit fullscreen mode

In the above example, you access your Twilio messaging service through a constant named Twilio and then call sendSms where you pass parameters i.e receiver phone number, message to be sent and then the callback function.

So this is how you can send an sms to a phone number using Twilio, hope it helps you. Thank you for reading through this article.

Top comments (0)