Codementor Events

Sending SMS with Twilio in a Node.js Application

Published Apr 07, 2020
Sending SMS with Twilio in a Node.js Application

With the increase in the number of mobile devices around the globe today, and numerous mobile applications available to us, SMS is becoming the de facto standard for verification.

Statista mobile phone user.png
Source: Statista

SMS comes in handy for verification purposes at various stages in our applications, this is especially a great option on mobile applications.
It should be noted that SMS is not only useful for verification purposes but can be essential across various business use cases such as operational/transactional alerts, order placements, etc. TextMagic has a comprehensive article on a number of SMS use cases for businesses here

Today, we are going to explore how to use Twilio for sending SMS in a Node.js application.

Prerequisites
To follow through this tutorial you must have the following:

Node JS
NPM
Postman
Code Editor (VsCode)
Twilio account

If you don’t have Node.js installed just head on to the official Node.js website to get a copy of Node.js for your platform. Once you install node.js you will automatically have npm installed.

Head over to Twilio now to get an account set up in less than 2 mins free of charge.

Getting started
To get started, create a new directory for the application by running the following command on the terminal:

cd desktop && mkdir send-sms-with-twilio && cd send-sms-with-twilio

The commands above
cd desktop - navigate to the desktop directory
mkdir send-sms-with-twilio - create a new directory named “send-sms-with-twilio”
cd send-sms-with-twilio - navigate into the newly created send-sms-with-twilio directory

Initialize the directory to create a package.json file by running:

npm init -y

Open the newly created folder in your editor of choice.
Your folder structure should now look like the one below:

folder structure.png

Create a simple Express server as shown below in an index.js file:

const express = require('express');

const app = express();

const port = 3000;

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

module.exports = app;

To demonstrate a simple use case of SMS in our application, we are going to create a simple user registration system and use Twilio to send an activation code to the user’s phone number.

N:B

The purpose of this tutorial is to show how to send SMS using Twilio in our Node.js application hence all the best practices of user registration are not considered.

In the index.js file, paste the following code:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json());

const port = 3000;

const userDatabase = [];

// Create user endpoint
app.post('/users', (req, res) => {
  const { email, password, phone } = req.body;
  const user = {
    email,
    password,
    phone
  };

  userDatabase.push(user);

  res.status(201).send({
    message: 'Account created successfully, kindly check your phone to activate your account!',
    data: user
  })
});

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

module.exports = app;

Now that we can create a user successfully, let’s now integrate Twilio to help us send verification SMS to new users as soon as their account is created. Head on to Twilio site and create your account. After you successfully created an account your dashboard should look similar to the one below:

Twilio dashboard.png

Get a Free Twilio trial number
From your Twilio dashboard, click Get a Trial Number to get a free number which we’ll use as the sender when sending out the SMS to users. You will be able to customize your SENDER ID once you upgrade your account by subscribing to the Twilio platform but our trial number will suffice for the purpose of this tutorial.

Integrating Twilio in our App
Create a new file in the project directory and name it twilio.js. In the new file copy and paste the following code:

require('dotenv').config();

const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;

const sendSms = (phone, message) => {
  const client = require('twilio')(accountSid, authToken);
  client.messages
    .create({
       body: message,
       from: process.env.TWILIO_PHONE_NUMBER,
       to: phone
     })
    .then(message => console.log(message.sid));
}

module.exports = sendSms;

Create a .env file at the root of your project and add your twilio auth key, account sid and phone number just as below:
Screenshot 2020-04-05 at 10.19.52 PM.png

NOTE:
Depending on the format you’re getting the phone number from your user, you may need to format it to meet the international format for sending and receiving SMS. Read more on that topic here

Now, in the index.js file, add the following code:

const express = require('express');
const bodyParser = require('body-parser');
const sendSms = require('./twilio');

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json());

const port = 3000;

const userDatabase = [];

// Create users endpoint
app.post('/users', (req, res) => {
  const { email, password, phone } = req.body;
  const user = {
    email,
    password,
    phone
  };

  userDatabase.push(user);

  const welcomeMessage = 'Welcome to Opalod! Your verification code is 54875';

  sendSms(user.phone, welcomeMessage);

  res.status(201).send({
    message: 'Account created successfully, kindly check your phone to activate your account!',
    data: user
  })
});

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

module.exports = app;

Now we are ready to send SMS in our node.js application so let us test our work

Testing our application

Just before we send our first SMS, we need to add a verified phone number to our Twilio account. This is so because we are on the trial version. So, from your Twilio dashboard, click on verify phone number and verify a phone.

You should have at least one verified phone number already if you set up your account properly.
Save your work and start the server by running node index.js on the terminal

Open up Postman and send a POST request to the /users endpoint with the right parameters

sendSMS Response.png

Sent SMS screenshot.png

Congratulations! You’ve just successfully sent an SMS from a Node.js application.

Twilio has a lot more to offer than just sending SMS to get more of their offerings, kindly visit their official documentation here

Complete code can be found here: https://github.com/iMichaelOwolabi/send-sms-with-twilio

Discover and read more posts from Michael Owolabi
get started