Parsing an Incoming Twilio SMS Webhook with Node.js

July 03, 2019
Written by
Sam Agnew
Twilion

Copy of Product Template - SMS-4.png

When responding to an incoming SMS message, you have access to a variety of information about the message through the body of the webhook request that Twilio sends you.

Here is all the code you need to grab data from an incoming SMS webhook request from the Twilio API and respond with another text message:

const http = require('http');
const express = require('express');
const { urlencoded } = require('body-parser');
const MessagingResponse = require('twilio').twiml.MessagingResponse;

const app = express();
app.use(urlencoded({ extended: false }));

app.post('/sms', (req, res) => {
  const twiml = new MessagingResponse();

  // Access the message body and the number it was sent from.
  console.log(`Incoming message from ${req.body.From}: ${req.body.Body}`);

  twiml.message('The Robots are coming! Head for the hills!');

  res.writeHead(200, {'Content-Type': 'text/xml'});
  res.end(twiml.toString());
});

http.createServer(app).listen(3000, () => {
  console.log('Express server listening on port 3000');
});

Simply responding to a text message may only involve returning some TwiML, but sometimes you might want to programmatically make decisions based on things like the body of the message or the country the message was sent from. As in the example above, this requires you to access information contained in the HTTP request sent from Twilio.

Let's walk through how to access this information in more detail with Node.js and the Express framework.

Development Environment Setup

Let's start by making sure we have the right software installed and set up that we'll need to use for the rest of this post. Throughout this post, you will need:

Here is a good guide to follow in general if you are going to be doing more with Twilio and Node.js and have any more questions.

To install these npm modules, navigate to the directory where you want this code to live and run the following command in your terminal to create an npm package for this project.

npm init --yes

The --yes argument just runs through all of the prompts that you would otherwise have to fill out or skip. Now that we have a package.json for our app, let’s install the necessary libraries with the following shell commands:

npm install twilio@3.33.0 --save
npm install express@4.17.0 --save
npm install body-parser@1.17.0 --save

After this you should be good to write some code!

Setting up an Express server to receive the incoming message

Open a file called index.js in the same directory as your package.json and add the following code to it:

const http = require('http');
const express = require('express');
const { urlencoded } = require('body-parser');
const MessagingResponse = require('twilio').twiml.MessagingResponse;

const app = express();
app.use(urlencoded({ extended: false }));

app.post('/sms', (req, res) => {
  const twiml = new MessagingResponse();

  // Access the message body and the number it was sent from.
  console.log(`Incoming message from ${req.body.From}: ${req.body.Body}`);

  twiml.message('The Robots are coming! Head for the hills!');

  res.writeHead(200, {'Content-Type': 'text/xml'});
  res.end(twiml.toString());
});

http.createServer(app).listen(3000, () => {
  console.log('Express server listening on port 3000');
});

This code sets up an Express app, defines a route on the app to handle incoming SMS messages, and then has it listen on port 3000 for incoming requests. In the /sms route, the body-parser middleware is used to access data in the request body in order to grab the text of the message and the phone number it was sent from.

You can run this code with the following command:

node index.js

Setting up your Twilio account

Before being able to respond to messages, you’ll need a Twilio phone number. You can buy a phone number here (it’s free if you’re using the number to test your code during development).

Your Express app will need to be visible from the internet in order for Twilio to send requests to it. We will use ngrok for this, which you’ll need to install if you don’t have it. In your terminal run the following command:

ngrok http 3000

If you’ve just installed ngrok and that previous command didn’t work, you might have to run it like ./ngrok http 3000 from the directory that the ngrok executable is in.

Screen Shot 2017-10-20 at 3.45.06 PM.png

This provides us with a publicly accessible URL to the Express app. Configure your phone number as seen in this image by adding your ngrok URL with "/sms" appended to it to the “Messaging” section:

Screen Shot 2017-10-20 at 3.45.41 PM.png

You are now ready to receive a text message to your new Twilio number.

What else can I do?

So you're grabbing the text of the message and the number it was sent from, but there is more information in the body of that request that you can use. If you want to find out which country the message was sent from you can do that with req.body.FromCountry. You can also grab the status of the message with req.body.SmsStatus.

If you want to learn more thoroughly about Express and Twilio SMS check out the SMS and MMS Notifications tutorial or Appointment Reminders with Express.

Feel free to reach out if you have any questions or comments or just want to show off the cool stuff you’ve built.