Build the future of communications.
Start building for free

Send a Text Message using JavaScript/Node.js in 30 seconds with Twilio

NodeSMSBanner

You’re building a Node app and you need to send text messages. Did you know it only takes you 30 seconds? Here’s a video to show you how quick it is to get started:

Video: How To Send SMS In Node 30 Seconds

You can’t copy and paste from a video, so here’s all of the code you would need with those three lines expanded in the way you’d write them in a normal Node app.

Note: The code below has been updated to use the latest version of the helper library.

var twilio = require('twilio');

// Find your account sid and auth token in your Twilio account Console.
var client = new twilio('TWILIO_ACCOUNT_SID', 'TWILIO_AUTH_TOKEN');

// Send the text message.
client.messages.create({
  to: 'YOUR_NUMBER',
  from: 'YOUR_TWILIO_NUMBER',
  body: 'Hello from Twilio!'
});

If you want to run that code, open a file called index.js, copy and paste that code and run the following in your terminal (from the same directory the file is saved in):

npm install twilio
node index.js

What just happened?

Now let’s walk through what happened in the video step by step.

Install the Twilio helper library for Node using npm.

npm install twilio

Open up a Node session by typing node in your terminal and require the twilio library.

var twilio = require('twilio');

Instantiate a REST client using your account sid and auth token, available in your Twilio account Console:

var client = new twilio('TWILIO_ACCOUNT_SID', 'TWILIO_AUTH_TOKEN');

In the video, I have those stored in environment variables to avoid showing my credentials to you. You can do that like so:

export TWILIO_ACCOUNT_SID='YOUR_ACCOUNT_SID'
export TWILIO_AUTH_TOKEN='YOUR_AUTH_TOKEN'

You’ll now need three things:

  • The number you are sending the message to
  • The Twilio number you are sending the message from
  • The body of the message

With these you can now send a text message by calling client.sendMessage():

client.messages.create({
  to: 'YOUR_NUMBER',
  from: 'YOUR_TWILIO_NUMBER',
  body: 'Ahoy from Twilio!'
});

Now just wait for the magic to happen!

We can’t wait to see what you build

You’ve sent a text message and now you’re ready to take on the world. Check out the Twilio REST API documentation and the documentation for working with the Node helper library to see what else you can do. You can also take a look at our tutorials to see more examples such as: sending SMS notifications, masking phone numbers for user privacy or two factor authentication for user security.

I’m looking forward to seeing what you all build. Feel free to reach out and share your experiences or ask any questions.

Authors
Sign up and start building
Not ready yet? Talk to an expert.