in twilio Node JavaScript API ~ read.

Send your first sms using Twilio and Nodejs

In this post we are going to talk about using Twilio and Nodejs to send SMS.

What is Twilio?

Twilio provides APIs for Text Messaging, VoIP & Voice in the Cloud. In a simple term we can use their API to send message, make a phone call etc. For free with the trial account.

Create your first Twilio account

Head over to their website and create a twilio account and confirm your number from Twilio. 3 key things we need to have from your account is 1) Account SID. 2) Auth Token. 3) Phone number. No worries all of them are free for trail account.

Set up our Nodejs environment.

For the sake of simplicity I am gonna use express generator to setup the basic environment. After install the generator using Nodejs, run the following command to get the template setup.

express twilio

Next let's install the package from the template using the following command.

npm install

Next let's install twilio npm package using the following command.

npm install --save twilio

Next let's run npm start to fire up the application.

Let's send our first SMS using Twilio!

Next let's modify our routes/index.js file like the following.

var express = require('express');  
var client  = require('twilio');  
var client  = new twilio.RestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN);  
var router  = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {  
  res.render('index', { title: 'Express' });
});

router.get('/sms', function(req, res) {  
  client.messages.create({
    body: 'Howdy',
    to  : YOUR_PHONE_NUMBER,
    from: TWILIO_NUMBER
  }, (err, message) => {
    if(err) console.log(err);
  });
});

module.exports = router;  

Let's have a look at the code. First we require the twilio package using require. And we provide the account sid and auth token from our twilio account in order to create a twilio client to send SMS.

Next we create en endpoint /sms. So if someone reach to this endpoint which will trigger the client to send message. Remember before we got a number from twilio as a trial account. We need to put that number into from value.

Next we need to restart the server since we've made some changes to the code. Type in the following command after ctrl+C.

npm start

Next when you navigate to your localhost:3000/sms page it will send you an sms using Twilio!

End

It is quite a short post for Twilio. But we are just scratching the surface, sure dive into the details of their APIs. There are tons of other stuff we can do using Twilio's API. As always if you have any comments or ideas please leave it below. Thanks for reading!

comments powered by Disqus