Programmable Voice quickstart for Node.js
This quickstart will show you how to build a Node.js application with Twilio's Node.js helper library.
Your application will make an outbound phone call and respond to an inbound phone call. It will use the Twilio REST API to make the outbound call, and TwiML to respond to the inbound call by reading a message using Text to Speech.
Sign up here to get a free Twilio trial account or log in to an account you already have.
If you don't have a Twilio phone number with voice call functionality then you'll need to buy one by doing the following:
- Go to the Buy a Number page.
- Check the Voice box.
- Click Search. You'll see a list of available phone numbers.
- Find the number you want, and click Buy next to a phone number to add it to your account.
Check if you already have Node.js installed on your computer by opening a command line and running the following command:
node -v
You should see something like:
1node -v2v22.14.0
You'll need Node.js version 14 or later to run this quickstart. If you don't have a matching version of Node.js on your computer then download and install it.
The easiest way to install the library is using npm, the Node.js package manager. Run the following command in a new directory:
npm install twilio
Let's put that Twilio Node.js library to good use. With a single API request, you can make an outbound call from your Twilio phone number.
Open a new file called make_call.js
and paste in the following code:
1// Download the helper library from https://www.twilio.com/docs/node/install2const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";34// Find your Account SID and Auth Token at twilio.com/console5// and set the environment variables. See http://twil.io/secure6const accountSid = process.env.TWILIO_ACCOUNT_SID;7const authToken = process.env.TWILIO_AUTH_TOKEN;8const client = twilio(accountSid, authToken);910async function createCall() {11const call = await client.calls.create({12from: "+987654321",13to: "+123456789",14url: "http://demo.twilio.com/docs/voice.xml",15});1617console.log(call.sid);18}1920createCall();
This code starts a phone call between the two phone numbers that you pass as arguments. The from
number is your Twilio number, and the to
number is who you want to call.
The url
argument points to a TwiML file that tells Twilio what to do when the call recipient answers their phone. This TwiML instructs Twilio to read a message using text to speech and then play an MP3.
Swap the placeholder values for accountSid
and authToken
with your personal Twilio credentials.
- Log in to the Twilio Console.
- Copy the Account SID and replace
process.env.TWILIO_ACCOUNT_SID
with it in themake_call.js
file. - Copy the Auth Token and replace
process.env.TWILIO_AUTH_TOKEN
with it.
Danger
This quickstart hardcodes your credentials to get you started quickly. Use environment variables and API keys to keep credentials secret and control access when you deploy to production.
Remember that 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]
Next, replace the to
phone number with your mobile phone number. As above, you should use E.164 formatting for this value. Save your changes and run the code by running the following command from your terminal:
node make_call.js
Your phone should ring with a call from your Twilio number.
Info
If you're using a Twilio trial account, outgoing phone calls are limited to phone numbers you have verified with Twilio. Phone numbers can be verified via your Twilio Console's Verified Caller IDs. For other trial account restrictions and limitations, check out our guide on how to work with your free Twilio trial account.
To handle incoming phone calls, we'll need a web application that can accept HTTP requests from Twilio.
On the command line, install the Express framework by running the below command:
npm install express --save
Now, create a file called server.js
and use the following code to create a server that can handle incoming messages:
1const express = require('express');2const VoiceResponse = require('twilio').twiml.VoiceResponse;34const app = express();56// Create a route that will handle Twilio webhook requests, sent as an7// HTTP POST to /voice in our application8app.post('/voice', (request, response) => {9// Use the Twilio Node.js SDK to build an XML response10const twiml = new VoiceResponse();1112twiml.say('Hello from your pals at Twilio! Have fun.');1314// Render the response as XML in reply to the webhook request15response.type('text/xml');16response.send(twiml.toString());17});1819// Create an HTTP server and listen for requests on port 133720app.listen(1337, () => {21console.log('TwiML server running at http://127.0.0.1:1337/');22});
Run this server with the following command:
node server.js
Open a web browser and visit http://127.0.0.1:1337/. You should see that the server responds with TwiML containing the message that we'd like to read to incoming calls.
If you don't already use ngrok then download and install it.
Start the server again if it's not still running:
node server.js
Then open a new command line window and start ngrok with this command:
ngrok http 1337
You should see output similar to this:
1Session Status online2Version 3.23.23Web Interface http://127.0.0.1:40404Forwarding https://ff4660c91380.ngrok.app -> http://localhost:133756Connections ttl opn rt1 rt5 p50 p9070 0 0.00 0.00 0.00 0.00
Copy the URL ending in ngrok.app
and paste it into your browser. You should see your Express application's "Hello from your pals at Twilio!" message.
- Navigate to the Active Numbers page in the Twilio Console.
- Click on the phone number you purchased earlier.
- Visit the Configure tab and find the Voice Configuration section.
- In the A call comes in row, select the Webhook option. Enter your ngrok public URL in the URL field (for example,
https://ff4660c91380.ngrok.app
). - Click on Save configuration.
Head back to your terminal. Make sure that ngrok is still running in one tab and your Express server is running in another tab.
Make a phone call to your Twilio phone number. Within a few moments, you'll see an HTTP request in your ngrok console, and you'll hear a short message once the call connects.
And there you go - you've successfully made and received a call with Node.js.
Your new application uses the <Say> TwiML verb to read a message to the caller using text to speech. You can create create more powerful constructs and call flows using other TwiML verbs. Try a few, such as <Record>, <Gather>, and <Conference>.
Check out these pages to learn more:
- Dig into the Programmable Voice API reference documentation
- Gather user input via keypad (DTMF tones) in Node.js
- Learn how to record incoming and outgoing Twilio Voice phone calls using Node.js and Express
- Create conference calls with Node.js
- Learn how to modify calls in progress
- Check out our full sample application tutorial on how to transfer calls from one support agent to another using Node.js and Express
Let's build something amazing.