How to send sms to a phone number in node.js
Published: 2022-03-11 15:00:18

<b>Twilio</b> 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
```
<b>Code (TwilioMessagingService.js)</b>
```javascript
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);
            }
        });
    },

}



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

Next step is to instantiate Twilio client by using <b>new twilio(accountSid, authToken)</b> 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 <b>sendSms()</b> which is used to send text message to a user phone number. Through an Twilio instance <b>client</b>, you can send a message using <b>messages.create()</b> function which takes in one parameter, a json object with keys <b>body</b> (the message to be sent to the user), <b>to</b> (a phone number that belongs to the user, receiving the message) and <b>from</b> (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.

<b>Calling sendSms</b>
You can call sendSms forexample using the code snippet below;

```javascript
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);
   });

}

```
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.