Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

Programmable Messaging Quickstart - Node.js


(information)

Info

Ahoy there! All messaging transmitted using Twilio's messaging channels is treated as Application-to-Person (A2P) messaging and subject to Twilio's Messaging Policy(link takes you to an external page). For detailed information on policy rules to ensure you remain compliant while using Twilio's services, please see our Acceptable Use Policy(link takes you to an external page).

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 Programmable Messaging 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 Messaging Quickstart video on Youtube(link takes you to an external page).


Sign up for Twilio and Get a Twilio Phone Number

sign-up-for-twilio-and-get-a-twilio-phone-number page anchor
(information)

Info

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.

(warning)

Warning

If you are sending SMS to the U.S. or Canada, before proceeding further please be aware of updated restrictions on the use of Toll-Free numbers for messaging, including TF numbers obtained through Free Trial. Please click here(link takes you to an external page) for details.

You can sign up for a free Twilio trial account here(link takes you to an external page).

  • When you sign up, you'll be asked to verify your personal phone number. This helps Twilio verify your identity and also allows you to send test messages to your phone from your Twilio account while in trial mode.
  • Once you verify your number, you'll be asked a series of questions to customize your experience.
  • Once you finish the onboarding flow, you'll arrive at your project dashboard in the Twilio Console(link takes you to an external page) . This is where you'll be able to access your Account SID, authentication token, find a Twilio phone number, and more.

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(link takes you to an external page) page, check the SMS box and click Search.

Buy a twilio phone number.

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.

Select an SMS-enabled phone number.

Install Node.js and the Twilio Module

install-nodejs-and-the-twilio-module page anchor
(information)

Info

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 Helper Library(link takes you to an external page) installed.

Install Node.js

install-nodejs page anchor

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


_10
node --version

You should see something like:


_10
$ node --version
_10
v18.1.2

If you don't have Node.js installed, head over to nodejs.org and download the appropriate installer for your system(link takes you to an external page). Once you've installed Node, return to your terminal and run the command above once again. If you don't see the installed node version, you may need to relaunch your terminal.

Install the Twilio Node.js Module

install-the-twilio-nodejs-module page anchor

Install the Twilio Node helper library using npm(link takes you to an external page):


_10
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

send-an-outbound-sms-message-with-nodejs page anchor

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.

Send an SMS Using Twilio with Node.js

send-an-sms-using-twilio-with-nodejs page anchor

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

Node.js

_14
// Download the helper library from https://www.twilio.com/docs/node/install
_14
// Find your Account SID and Auth Token at twilio.com/console
_14
// and set the environment variables. See http://twil.io/secure
_14
const accountSid = process.env.TWILIO_ACCOUNT_SID;
_14
const authToken = process.env.TWILIO_AUTH_TOKEN;
_14
const client = require('twilio')(accountSid, authToken);
_14
_14
client.messages
_14
.create({
_14
body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
_14
from: '+15017122661',
_14
to: '+15558675310'
_14
})
_14
.then(message => console.log(message.sid));

Output

_24
{
_24
"account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_24
"api_version": "2010-04-01",
_24
"body": "This is the ship that made the Kessel Run in fourteen parsecs?",
_24
"date_created": "Thu, 24 Aug 2023 05:01:45 +0000",
_24
"date_sent": "Thu, 24 Aug 2023 05:01:45 +0000",
_24
"date_updated": "Thu, 24 Aug 2023 05:01:45 +0000",
_24
"direction": "outbound-api",
_24
"error_code": null,
_24
"error_message": null,
_24
"from": "+15017122661",
_24
"num_media": "0",
_24
"num_segments": "1",
_24
"price": null,
_24
"price_unit": null,
_24
"messaging_service_sid": "MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_24
"sid": "SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_24
"status": "queued",
_24
"subresource_uris": {
_24
"media": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Media.json"
_24
},
_24
"to": "+15558675310",
_24
"uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json"
_24
}

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

Replace the placeholder credential values

replace-the-placeholder-credential-values page anchor

Swap the placeholder values for accountSid and authToken with your personal Twilio credentials. Go to https://www.twilio.com/console(link takes you to an external page) 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.

auth token reveal.

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

(error)

Danger

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(link takes you to an external page) for more information.

Replace the "from" phone number

replace-the-from-phone-number page anchor

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 page anchor

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:


_10
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.

(warning)

Warning

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(link takes you to an external page).


Receive and Reply to Inbound SMS Messages with Express

receive-and-reply-to-inbound-sms-messages-with-express page anchor

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(link takes you to an external page).

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


_10
npm install express

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

Respond to an incoming text message

respond-to-an-incoming-text-message page anchor

When your Twilio phone number receives an incoming message, Twilio will send an HTTP request to your server. This code shows how your server can reply with a text message using the Twilio helper library.

Node.js
Python
C#
Java
Go
PHP
Ruby

_16
const express = require('express');
_16
const { MessagingResponse } = require('twilio').twiml;
_16
_16
const app = express();
_16
_16
app.post('/sms', (req, res) => {
_16
const twiml = new MessagingResponse();
_16
_16
twiml.message('The Robots are coming! Head for the hills!');
_16
_16
res.type('text/xml').send(twiml.toString());
_16
});
_16
_16
app.listen(3000, () => {
_16
console.log('Express server listening on port 3000');
_16
});

Run this server with the following command:


_10
node server.js

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

Before Twilio can send your application webhook requests, you'll need to make your application accessible over the Internet. While you can do that in any number of ways, we recommend using the Twilio CLI during local development. We'll show you how to set that up next so your app can receive messages.


macOSWindowsLinux

The suggested way to install twilio-cli on macOS is to use Homebrew(link takes you to an external page). If you don't already have it installed, visit the Homebrew site(link takes you to an external page) for installation instructions and then return here.

Once you have installed Homebrew, run the following command to install twilio-cli:


_10
brew tap twilio/brew && brew install twilio

(information)

Info

For other installation methods, see the Twilio CLI Quickstart.

Run twilio login to get the Twilio CLI connected to your account. Visit https://www.twilio.com/console(link takes you to an external page), and you'll find your unique Account SID and Auth Token to provide to the CLI.

You can reveal your auth token by clicking on the eyeball icon:

Reveal Your Auth Token.

Now, you can use the CLI to connect your phone number to your Node.js app.

Configure Your Webhook URL

configure-your-webhook-url page anchor

Now, you need to configure your Twilio phone number to call your webhook URL whenever a new message comes in. Just run this CLI command, replacing the phone number with your Twilio phone number:


_10
twilio phone-numbers:update "+15017122661" --sms-url="http://localhost:1337/sms"

(information)

Info

What's happening here?

whats-happening-here page anchor

We're using the Twilio CLI to set the SMS webhook URL for your phone number. Twilio will make a request to this URL whenever a new SMS message is received. The CLI is also using ngrok(link takes you to an external page) to create a tunnel to allow Twilio to reach your local development server (aka "localhost").

You can also use the Twilio Console(link takes you to an external page) to set a webhook in your web browser, but you will have to start up ngrok yourself(link takes you to an external page).

Make sure you are running on the command line (in separate tabs) both node server.js and your twilio command.

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.


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!


Rate this page: