Programmable Voice Quickstart for Node.js

Programmable Voice allows you to make and receive phone calls in your Node.js applications. Let's see how it's done!

Getting started

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

Search for voice capable numbers

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

Making a phone call

 

Let's put that shiny new Twilio Node.js library to good use. With a single API request, we can make an outbound call from the Twilio phone number we just purchased. Open a new file called "make_call.js" and paste in the following code.

 

Loading Code Samples...
Language
SDK Version:
  • 2.x
  • 3.x
Format:
  • JSON
  • XML
// Download the Node helper library from twilio.com/docs/node/install
// These consts are your accountSid and authToken from twilio.com/user/account
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const Twilio = require('twilio');
const client = new Twilio(accountSid, authToken);

client.api.calls
  .create({
    url: 'http://demo.twilio.com/docs/voice.xml',
    to: '+14155551212',
    from: '+15017250604',
  })
  .then((call) => console.log(call.sid));
// Download the Node helper library from twilio.com/docs/node/install
// These vars are your accountSid and authToken from twilio.com/user/account
var accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var authToken = "your_auth_token";
var client = require('twilio')(accountSid, authToken);

client.calls.create({
    url: "http://demo.twilio.com/docs/voice.xml",
    to: "+14155551212",
    from: "+15017250604"
}, function(err, call) {
    console.log(call.sid);
});
{
	"sid": "CAa346467ca321c71dbd5e12f627deb854",
	"date_created": "Thu, 19 Aug 2010 00:12:15 +0000",
	"date_updated": "Thu, 19 Aug 2010 00:12:15 +0000",
	"parent_call_sid": null,
	"account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
	"to": "+14155551212",
	"formatted_to": "(415) 555-1212",
	"from": "+14158675309",
	"formatted_from": "(415) 867-5309",
	"phone_number_sid": "PNd6b0e1e84f7b117332aed2fd2e5bbcab",
	"status": "queued",
	"start_time": null,
	"end_time": null,
	"duration": null,
	"price": null,
	"direction": "outbound-api",
	"answered_by": null,
	"api_version": "2010-04-01",
	"forwarded_from": null,
	"caller_name": null,
	"uri": "\/2010-04-01\/Accounts\/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\/Calls\/CAa346467ca321c71dbd5e12f627deb854.json",
	"subresource_uris": {
		"notifications": "\/2010-04-01\/Accounts\/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\/Calls\/CAa346467ca321c71dbd5e12f627deb854\/Notifications.json",
		"recordings": "\/2010-04-01\/Accounts\/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\/Calls\/CAa346467ca321c71dbd5e12f627deb854\/Recordings.json"
	}
}
<TwilioResponse>
	<Call>
		<Sid>CAa346467ca321c71dbd5e12f627deb854</Sid>
		<DateCreated>Thu, 19 Aug 2010 00:25:48 +0000</DateCreated>
		<DateUpdated>Thu, 19 Aug 2010 00:25:48 +0000</DateUpdated>
		<ParentCallSid/>
		<AccountSid>ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</AccountSid>
		<To>+14155551212</To>
		<FormattedTo>(415) 555-1212</FormattedTo>
		<From>+14158675309</From>
		<FormattedFrom>(415) 867-5309</FormattedFrom>
		<PhoneNumberSid></PhoneNumberSid>
		<Status>queued</Status>
		<StartTime/>
		<EndTime/>
		<Duration/>
		<Price/>
		<Direction>outbound-api</Direction>
		<AnsweredBy/>
		<ApiVersion>2010-04-01</ApiVersion>
		<ForwardedFrom/>
		<CallerName/>
		<Uri>/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAa346467ca321c71dbd5e12f627deb854</Uri>
		<SubresourceUris>
			<Notifications>/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAa346467ca321c71dbd5e12f627deb854/Notifications</Notifications>
			<Recordings>/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAa346467ca321c71dbd5e12f627deb854/Recordings</Recordings>
		</SubresourceUris>
	</Call>
</TwilioResponse>
Make an outbound call

Update the account credentials and phone numbers with your own account information. Run the code with "node make_call.js" - in a moment, an outbound call will be made from your Twilio number! The URL parameter in this code sample returns an XML document containing TwiML - instructions that tell Twilio how to handle a phone call. You'll use TwiML to handle incoming phone calls as well, which we dive into next!

Receiving phone calls

When your Twilio number receives an incoming phone call, it 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 call. Let's see how we would build this in Node.js using the Express framework. 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
const http = require('http');
const VoiceResponse = require('twilio').twiml.VoiceResponse;

http
  .createServer((req, res) => {
    // Create TwiML response
    const twiml = new VoiceResponse();

    twiml.say('Hello from your pals at Twilio! Have fun.');

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

console.log('TwiML server running at http://127.0.0.1:1337/');
const http = require('http');
const twilio = require('twilio');

http
  .createServer((req, res) => {
    // Create TwiML response
    const twiml = new twilio.TwimlResponse();
    twiml.say('Hello from your pals at Twilio! Have fun.');

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

console.log("TwiML servin' server running at http://127.0.0.1:1337/");
Generate TwiML to Say a message

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. The following command would use ngrok to expose port 1337 to the public Internet.

ngrok http 1337

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

Voice Webhook in Twilio Console

Call your Twilio phone number -  you should see an HTTP POST request in your ngrok console. You should start hearing the TwiML instructions configured in our application executing, reading back a message using the <Say> tag.

Where to next?

Now that you know the basics of making phone calls with Node.js, you can consult the REST API and TwiML reference docs, or check out Tutorials with full Node.js sample apps. 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
// Download the Node helper library from twilio.com/docs/node/install
// These consts are your accountSid and authToken from twilio.com/user/account
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const Twilio = require('twilio');
const client = new Twilio(accountSid, authToken);

client.api.calls
  .create({
    url: 'http://demo.twilio.com/docs/voice.xml',
    to: '+14155551212',
    from: '+15017250604',
  })
  .then((call) => console.log(call.sid));
// Download the Node helper library from twilio.com/docs/node/install
// These vars are your accountSid and authToken from twilio.com/user/account
var accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
var authToken = "your_auth_token";
var client = require('twilio')(accountSid, authToken);

client.calls.create({
    url: "http://demo.twilio.com/docs/voice.xml",
    to: "+14155551212",
    from: "+15017250604"
}, function(err, call) {
    console.log(call.sid);
});
{
	"sid": "CAa346467ca321c71dbd5e12f627deb854",
	"date_created": "Thu, 19 Aug 2010 00:12:15 +0000",
	"date_updated": "Thu, 19 Aug 2010 00:12:15 +0000",
	"parent_call_sid": null,
	"account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
	"to": "+14155551212",
	"formatted_to": "(415) 555-1212",
	"from": "+14158675309",
	"formatted_from": "(415) 867-5309",
	"phone_number_sid": "PNd6b0e1e84f7b117332aed2fd2e5bbcab",
	"status": "queued",
	"start_time": null,
	"end_time": null,
	"duration": null,
	"price": null,
	"direction": "outbound-api",
	"answered_by": null,
	"api_version": "2010-04-01",
	"forwarded_from": null,
	"caller_name": null,
	"uri": "\/2010-04-01\/Accounts\/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\/Calls\/CAa346467ca321c71dbd5e12f627deb854.json",
	"subresource_uris": {
		"notifications": "\/2010-04-01\/Accounts\/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\/Calls\/CAa346467ca321c71dbd5e12f627deb854\/Notifications.json",
		"recordings": "\/2010-04-01\/Accounts\/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\/Calls\/CAa346467ca321c71dbd5e12f627deb854\/Recordings.json"
	}
}
<TwilioResponse>
	<Call>
		<Sid>CAa346467ca321c71dbd5e12f627deb854</Sid>
		<DateCreated>Thu, 19 Aug 2010 00:25:48 +0000</DateCreated>
		<DateUpdated>Thu, 19 Aug 2010 00:25:48 +0000</DateUpdated>
		<ParentCallSid/>
		<AccountSid>ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</AccountSid>
		<To>+14155551212</To>
		<FormattedTo>(415) 555-1212</FormattedTo>
		<From>+14158675309</From>
		<FormattedFrom>(415) 867-5309</FormattedFrom>
		<PhoneNumberSid></PhoneNumberSid>
		<Status>queued</Status>
		<StartTime/>
		<EndTime/>
		<Duration/>
		<Price/>
		<Direction>outbound-api</Direction>
		<AnsweredBy/>
		<ApiVersion>2010-04-01</ApiVersion>
		<ForwardedFrom/>
		<CallerName/>
		<Uri>/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAa346467ca321c71dbd5e12f627deb854</Uri>
		<SubresourceUris>
			<Notifications>/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAa346467ca321c71dbd5e12f627deb854/Notifications</Notifications>
			<Recordings>/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls/CAa346467ca321c71dbd5e12f627deb854/Recordings</Recordings>
		</SubresourceUris>
	</Call>
</TwilioResponse>
SDK Version:
  • 2.x
  • 3.x
const http = require('http');
const VoiceResponse = require('twilio').twiml.VoiceResponse;

http
  .createServer((req, res) => {
    // Create TwiML response
    const twiml = new VoiceResponse();

    twiml.say('Hello from your pals at Twilio! Have fun.');

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

console.log('TwiML server running at http://127.0.0.1:1337/');
const http = require('http');
const twilio = require('twilio');

http
  .createServer((req, res) => {
    // Create TwiML response
    const twiml = new twilio.TwimlResponse();
    twiml.say('Hello from your pals at Twilio! Have fun.');

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

console.log("TwiML servin' server running at http://127.0.0.1:1337/");