Programmable SMS Quickstart for Node.js

With just a few lines of code, your Node.js application can send and receive text messages with Twilio Programmable SMS.

This Node.js SMS Quickstart will teach you how to do this using our Communications REST API and the Twilio Node.js helper library.

In this Quickstart, you will learn how to:

  1. Sign up for Twilio and get your first SMS-enabled Twilio phone number
  2. Set up your development environment to send and receive messages
  3. Send your first SMS
  4. Receive inbound text messages
  5. Reply to incoming messages with an SMS

Prefer to get started by watching a video? Check out our Node.js SMS Quickstart video on Youtube.

If you already have a Twilio account and an SMS-enabled Twilio phone number, you’re all set here! Feel free to jump to the next step.

Before you can send an SMS from Node.js, you'll need to sign up for a Twilio account or sign into your existing account and purchase an SMS-capable phone number.

If you don't currently own a Twilio phone number with SMS functionality, you'll need to purchase one.  After navigating to the Buy a Number page, check the "SMS" box and click "Search."

You’ll then see a list of available phone numbers and their capabilities. Find a number that suits your fancy and click "Buy" to add it to your account.

Now that you have a Twilio account and a programmable phone number, you can start writing some code! To make things even easier, we'll next install Twilio's official helper for Node.js applications.

If you’ve gone through one of our other Node.js Quickstarts already and have Node.js and the Twilio Node.js helper library installed, you can skip this step and get straight to sending your first text message.

To send your first SMS, you’ll need to have Node.js and the Twilio Node.js module installed.

Install Node.js

You can check if you already have Node.js installed on your machine by opening up a terminal and running the following command:

node --version

You should see something like:

$ node --version
v8.9.1

If you don't have Node.js already installed, you can install it with homebrew, another package manager by going into your terminal and typing this on the command line:

brew install node

If you have a Windows machine, you should install nvm-windows to install both Node.js as well as npm, the Node.js package manager.

Install the Twilio Node.js Module

The easiest way to install the library is using npm, the Node.js package manage that lets you install the libraries you need. Simply run this in the terminal:

npm install twilio

This will install the twilio module so that Node.js scripts in the current directory can use it.

Send an Outbound SMS Message with Node.js

Now that we have Node.js and the Twilio Node.js library installed, we can send an outbound text message from the Twilio phone number we just purchased with a single API request. Create and open a new file called send_sms.js and type or paste in this code sample.

Loading Code Samples...
Language
SDK Version:
  • 2.x
  • 3.x
Format:
  • JSON
  • XML
// Twilio Credentials
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';

// require the Twilio module and create a REST client
const client = require('twilio')(accountSid, authToken);

client.messages.create(
  {
    to: '+15558675310',
    from: '+15017122661',
    body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
  },
  (err, message) => {
    console.log(message.sid);
  }
);
// Twilio Credentials
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';

// require the Twilio module and create a REST client
const client = require('twilio')(accountSid, authToken);

client.messages
  .create({
    to: '+15558675310',
    from: '+15017122661',
    body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
  })
  .then(message => console.log(message.sid));
{
  "sid": "MMc781610ec0b3400c9e0cab8e757da937",
  "date_created": "Mon, 19 Oct 2015 07:07:03 +0000",
  "date_updated": "Mon, 19 Oct 2015 07:07:03 +0000",
  "date_sent": null,
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "to": "+15558675310",
  "from": "+15017122661",
  "body": "This is the ship that made the Kessel Run in fourteen parsecs?",
  "status": "queued",
  "num_segments": "1",
  "num_media": "0",
  "direction": "outbound-api",
  "api_version": "2010-04-01",
  "price": null,
  "price_unit": "USD",
  "error_code": null,
  "error_message": null,
  "uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMc781610ec0b3400c9e0cab8e757da937.json",
}
<?xml version='1.0' encoding='UTF-8'?>
<TwilioResponse>
<Message>
  <Sid>MMc781610ec0b3400c9e0cab8e757da937</Sid>
  <DateCreated>Mon, 19 Oct 2015 07:09:09 +0000</DateCreated>
  <DateUpdated>Mon, 19 Oct 2015 07:09:09 +0000</DateUpdated>
  <DateSent/>
  <AccountSid>ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</AccountSid>
  <To>+15558675310</To>
  <From>+15017122661</From>
  <Body>This is the ship that made the Kessel Run in fourteen parsecs?</Body>
  <Status>queued</Status>
  <NumSegments>1</NumSegments>
  <NumMedia>0</NumMedia>
  <Direction>outbound-api</Direction>
  <ApiVersion>2010-04-01</ApiVersion>
  <Price/>
  <PriceUnit>USD</PriceUnit>
  <ErrorCode/>
  <ErrorMessage/>
  <Uri>/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMf1150fe5baf04104a39c3f311a053e4e.xml</Uri>
  <SubresourceUris/>
</Message>
</TwilioResponse>
This code creates a new instance of the Message resource and sends an HTTP POST to the Messages resource URI.
Send an SMS Using Twilio with Node.js

This code creates a new instance of the Message resource and sends an HTTP POST to the Messages resource URI.

You’ll need to edit this file a little more before your message will send:

Replace the placeholder credential values

Swap the placeholder values for accountSid and authToken with your personal Twilio credentials. Go to https://www.twilio.com/console and log in. On this page, you’ll find your unique Account SID and Auth Token, which you’ll need any time you send messages through the Twilio Client like this. You can reveal your auth token by clicking on the eyeball icon:

Open send_sms.js and replace the values for accountSid and authToken  with your unique values.

Please note: it's okay to hardcode your credentials when getting started, but you should use environment variables to keep them secret before deploying to production. Check out how to set environment variables for more information.

Replace the "from" phone number

Remember that SMS-enabled phone number you bought just a few minutes ago? Go ahead and replace the existing from number with that one, making sure to use E.164 formatting:

[+][country code][phone number including area code]

Replace the "to" phone number

Replace the to phone number with your mobile phone number. This can be any phone number that can receive text messages, but it’s a good idea to test with your own phone so you can see the magic happen! As above, you should use E.164 formatting for this value.

Save your changes and run this script from your terminal:

node send_sms.js

That's it! In a few moments, you should receive an SMS from your Twilio number on your phone.

Are your customers in the U.S. or Canada? You can also send them MMS messages by adding just one line of code. Check out this guide to sending MMS to see how it's done.

If you are on a Twilio Trial account, your outgoing SMS messages are limited to phone numbers that you have verified with Twilio. Phone numbers can be verified via your Twilio Console's Verified Caller IDs.

Receive and Reply to Inbound SMS Messages with Express

When your Twilio number receives an incoming message, Twilio will send an HTTP request to a server you control. This callback mechanism is known as a webhook.  When Twilio sends your application a request, it expects a response in the TwiML XML format telling it how to respond to the message. Let's see how we would build this in Node.js using Express.

On the command line in your current directory, run the following command:

npm install express

Create a file called server.js and use the following code to create a server that can handle incoming messages.

Loading Code Samples...
Language
SDK Version:
  • 2.x
  • 3.x
Format:
  • XML
var http = require('http');
var express = require('express');
var twilio = require('twilio');

var app = express();

app.post('/sms', function(req, res) {
  var twilio = require('twilio');
  var twiml = new twilio.TwimlResponse();
  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(1337, function () {
  console.log("Express server listening on port 1337");
});
const http = require('http');
const express = require('express');
const MessagingResponse = require('twilio').twiml.MessagingResponse;

const app = express();

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

  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(1337, () => {
  console.log('Express server listening on port 1337');
});
<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Message>The Robots are coming! Head for the hills!</Message>
</Response>
When your phone number receives an incoming message, Twilio will send an HTTP request to your server. This code shows how your server should respond to reply with a text message (using TwiML).
Respond to an incoming text message

When your phone number receives an incoming message, Twilio will send an HTTP request to your server. This code shows how your server should respond to reply with a text message (using TwiML).

Run this server with the following command:

node server.js

You'll see that the server starts up on port 1337.

You'll need to make your application accessible over the internet. While you can do that in any number of ways, we recommend a tool that provides an externally accessible URL called ngrok. We'll show you how to set that up next so your app can receive messages.

Allow Twilio to Talk to Your Node.js Application with ngrok

We’ve just built a small Express application to receive incoming messages. Before it will work, we need to make sure that Twilio can reach your application.

Most Twilio services use webhooks to communicate with your application. When Twilio receives an SMS, for example, it reaches out to a URL in your application for instructions on how to handle the message.

When you’re working on your Express application in your development environment, your app is only reachable by other programs on your computer, so Twilio won’t be able to talk to it. We need to solve this problem by making your application accessible over the internet.

While there are a lot of ways to do this, like deploying your application to Heroku or AWS, you'll probably want a less laborious way to test your Twilio application. For a lightweight way to make your app available on the internet, we recommend a tool called ngrokNgrok listens on the same port that your local web server is running on and provides a unique URL on the ngrok.io domain, forwarding incoming requests to your local development environment. It works something like this:

How ngrok helps Twilio reach your local server

 

If you haven't already, install ngrok. Make sure it's the ngrok version that’s appropriate for your operating system and take care that the `ngrok` command is on your system path. If you're working on a Mac or Linux, you're all set. If you're on Windows, follow our guide on how to install and configure ngrok on Windows. For more info on ngrok, including some great tips and tricks, check out this in-depth blog post.

The following command would use ngrok to expose port 1337 to the public Internet. Replace 1337 with whatever port number you used in your Express app, and type the following command on the command line:

ngrok http 1337

ngrok terminal output

Now we have a new external URL.

Configure Your Webhook URL

For Twilio to know where to look, you need to configure your Twilio phone number to call your webhook URL whenever a new message comes in.

  1. Log into Twilio.com and go to the Console's Numbers page.
  2. Click on your SMS-enabled phone number.
  3. Find the Messaging section. The default “CONFIGURE WITH” is what you’ll need: "Webhooks/TwiML".
  4. In the “A MESSAGE COMES IN” section, select "Webhook" and paste in your URL: in this quickstart step above, it would be: https://aaf29606.ngrok.io/sms - be sure to add `/sms` at the end.

configure-phone-number

 Save your changes - you’re ready!

Test Your Application

Make sure you are running on the command line (in separate tabs) both 'node server.js' and your 'ngrok' command. If you restarted ngrok, you will have to update your webhook in the console to use the right url.

With both of those servers running, we’re ready for the fun part - testing our new Express application! 

Send an SMS from your mobile phone to your Twilio phone number that's configured with this webhook. You should see an HTTP request in your ngrok console. Your Express app will process the text message, and you’ll get your response back as an SMS.

Where to next?

Now that you know the basics of sending and receiving SMS and MMS text messages with Node.js, you might want to check out these resources.

Happy hacking!

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

Loading Code Samples...
SDK Version:
  • 2.x
  • 3.x
Format:
  • JSON
  • XML
// Twilio Credentials
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';

// require the Twilio module and create a REST client
const client = require('twilio')(accountSid, authToken);

client.messages.create(
  {
    to: '+15558675310',
    from: '+15017122661',
    body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
  },
  (err, message) => {
    console.log(message.sid);
  }
);
// Twilio Credentials
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';

// require the Twilio module and create a REST client
const client = require('twilio')(accountSid, authToken);

client.messages
  .create({
    to: '+15558675310',
    from: '+15017122661',
    body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
  })
  .then(message => console.log(message.sid));
{
  "sid": "MMc781610ec0b3400c9e0cab8e757da937",
  "date_created": "Mon, 19 Oct 2015 07:07:03 +0000",
  "date_updated": "Mon, 19 Oct 2015 07:07:03 +0000",
  "date_sent": null,
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "to": "+15558675310",
  "from": "+15017122661",
  "body": "This is the ship that made the Kessel Run in fourteen parsecs?",
  "status": "queued",
  "num_segments": "1",
  "num_media": "0",
  "direction": "outbound-api",
  "api_version": "2010-04-01",
  "price": null,
  "price_unit": "USD",
  "error_code": null,
  "error_message": null,
  "uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMc781610ec0b3400c9e0cab8e757da937.json",
}
<?xml version='1.0' encoding='UTF-8'?>
<TwilioResponse>
<Message>
  <Sid>MMc781610ec0b3400c9e0cab8e757da937</Sid>
  <DateCreated>Mon, 19 Oct 2015 07:09:09 +0000</DateCreated>
  <DateUpdated>Mon, 19 Oct 2015 07:09:09 +0000</DateUpdated>
  <DateSent/>
  <AccountSid>ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</AccountSid>
  <To>+15558675310</To>
  <From>+15017122661</From>
  <Body>This is the ship that made the Kessel Run in fourteen parsecs?</Body>
  <Status>queued</Status>
  <NumSegments>1</NumSegments>
  <NumMedia>0</NumMedia>
  <Direction>outbound-api</Direction>
  <ApiVersion>2010-04-01</ApiVersion>
  <Price/>
  <PriceUnit>USD</PriceUnit>
  <ErrorCode/>
  <ErrorMessage/>
  <Uri>/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMf1150fe5baf04104a39c3f311a053e4e.xml</Uri>
  <SubresourceUris/>
</Message>
</TwilioResponse>
SDK Version:
  • 2.x
  • 3.x
Format:
  • XML
var http = require('http');
var express = require('express');
var twilio = require('twilio');

var app = express();

app.post('/sms', function(req, res) {
  var twilio = require('twilio');
  var twiml = new twilio.TwimlResponse();
  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(1337, function () {
  console.log("Express server listening on port 1337");
});
const http = require('http');
const express = require('express');
const MessagingResponse = require('twilio').twiml.MessagingResponse;

const app = express();

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

  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(1337, () => {
  console.log('Express server listening on port 1337');
});
<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Message>The Robots are coming! Head for the hills!</Message>
</Response>