Programmable SMS Quickstart for Node.js

Programmable SMS allows you to send and receive text messages in your Node.js applications. With a few lines of code, your web application can send messages from (and receive messages sent to) your own programmable phone number.

Get a Twilio phone number

Before you can send an SMS from Node.js, you'll need to sign up for a Twilio account and purchase an SMS-capable phone number. When you search for a number to buy, you'll be able to see what types of communication it can power.

Buy SMS Capable Number

Click "Buy" to add one of these numbers to your account.  Now that you have a Twilio account and a programmable phone number, you can start writing some code! To make things easier, we'll install Twilio's official helper for Node.js applications.

Install the Twilio Node.js module

Next, we'll install the Twilio module for Node.js. Fire up a terminal / command line interface on your machine that already has Node and npm installed, and run the following command in a new directory.

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 

Let's put that shiny new Twilio Node.js library to good use. With a single API request, we can send an outbound text message from the Twilio phone number we just purchased. Open a new file called send-sms.js and paste in this code sample.

Loading Code Samples...
Language
SDK Version:
  • 2.x
  • 3.x
Format:
  • JSON
  • XML
// Twilio Credentials 
var accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; 
var authToken = 'your_auth_token'; 
 
//require the Twilio module and create a REST client 
var client = require('twilio')(accountSid, authToken); 
 
client.messages.create({ 
    to: "+15558675309", 
    from: "+15017250604", 
    body: "This is the ship that made the Kessel Run in fourteen parsecs?", 
}, function(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: '+15558675309',
    from: '+15017250604',
    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": "+15558675309",
  "from": "+15017250604",
  "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>+15558675309</To>
  <From>+15017250604</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>
Send an SMS using the Programmable SMS API

Update the account credentials with your own account information. Specify your new Twilio number in the from parameter, and your own mobile number in the to parameter. Run the code we just created with this command.

node send-sms.js

In a few moments, you should receive an SMS from your Twilio number on your phone.

Receive inbound SMS messages

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. 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. Unfortunately, Twilio can't directly call a server running on your computer - you'll either need to deploy this code to a public server, or run a tunnel such as ngrok that provides an externally accessible URL. We'll show you how to set that up next.

Allow Twilio to talk to your Node application

If you haven't already, install ngrok and ensure the ngrok command is on your system path. 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.

ngrok http 1337

ngrok terminal output

Now we have a new external URL.  Configure this as a webhook for one of your phone numbers in the console. Select your phone number, change "A MESSAGE COMES IN" to "Webhook", and then put in the external URL to your service, such as https://sadfs3423.ngrok.io/sms.

SMS webhook with /sms route

Send a text message to your Twilio phone number -  you should see an HTTP request in your ngrok console. Your Node.js app will process the text message, and you'll get a response back as an SMS.

Where to next?

Now that you know the basics of sending and receiving 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.

1 / 1
Loading Code Samples...
SDK Version:
  • 2.x
  • 3.x
Format:
  • JSON
  • XML
// Twilio Credentials 
var accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; 
var authToken = 'your_auth_token'; 
 
//require the Twilio module and create a REST client 
var client = require('twilio')(accountSid, authToken); 
 
client.messages.create({ 
    to: "+15558675309", 
    from: "+15017250604", 
    body: "This is the ship that made the Kessel Run in fourteen parsecs?", 
}, function(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: '+15558675309',
    from: '+15017250604',
    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": "+15558675309",
  "from": "+15017250604",
  "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>+15558675309</To>
  <From>+15017250604</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>