Making Phone calls with the help of Twilio in Node.js application

In today's applications we need functionalities to make calls and receive calls. You need to meet the below requirements before we start.

  • Set up a free Twilio account.

  • Node.js 

  • A phone to test the project.

First step is to set up a new Node.js Project. In a new directory open a terminal or command prompt and type the following commands.

mkdir nodejs-phone-call
cd nodejs-phone-call

Then install Twilio Node Helper Library with the following command line.

npm install twilio

Your Node.js project needs your Twilio credentials like Account SID and Auth Token. Create a .env file in your project and add these credentials in it. Set TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN as environment variables to store the values. Then buy a Twilio number. You can provide instructions using Twilio markup language TwiML. When someone makes a call to your Twilio number, Twilio looks up the URL associated with your number and sends a request to the URL. Twilio will follow the instructions sent using TwiML. You can host TwiML through Twilio in a TwiML Bin. To create a new TwiML Bin click create new TwiML Bin button. You will be redirected to a new page where you can configure your bin. You should give a name to your bin first then copy and paste the following TwiML into the TwiML field .

<?xml version="1.0" encoding="UTF-8"?>

<Response>

  <Say>Hello, from Node.js!</Say>

</Response>

Then click the create button and copy the URL. To make a phone call, create a new JavaScript file in the Nodejs-phone -call directory which you created at the beginning. Paste the following code in the JavaScript file.

require('dotenv').config();


const accountSid = process.env.TWILIO_ACCOUNT_SID;

const authToken = process.env.TWILIO_AUTH_TOKEN;

const client = require('twilio')(accountSid, authToken);


client.calls

  .create({

    from:'<YOUR_TWILIO_PHONE_NUMBER>',

    to:'<YOUR_PHONE_NUMBER>',     

    url: '<YOUR_TWIML_BIN_URL>'

  })

  .then(call => console.log(call.sid));

Update the above code with Twilio Phone number, personal phone number, URL you copied from TwiML bin.

Run the script using the below given command.

node make-call.js