Skip to contentSkip to navigationSkip to topbar
On this page

Receive an incoming phone call


When someone calls your Twilio number, Twilio can invoke a webhook that you've created to determine how to respond using TwiML. On this page, we will be providing some examples of Functions that can serve as the webhook of your Twilio number.

A Function that responds to webhook requests will receive details about the incoming phone call as properties on the event parameter. These include the phone number of the caller (event.From), the phone number of the recipient (event.To), and other relevant data such as geographic metadata about the phone numbers involved. You can view a full list of potential values at Twilio's request to your application.

Once a Function has been invoked on an incoming phone call, any number of actions can be taken. Below are some examples to inspire what you will build.


Create and host a Function

create-and-host-a-function page anchor

In order to run any of the following examples, you will first need to create a Function into which you can paste the example code. You can create a Function using the Twilio Console or the Serverless Toolkit as explained below:

ConsoleServerless Toolkit

If you prefer a UI-driven approach, creating and deploying a Function can be done entirely using the Twilio Console and the following steps:

  1. Log in to the Twilio Console and navigate to the Functions tab(link takes you to an external page). If you need an account, you can sign up for a free Twilio account here(link takes you to an external page)!
  2. Functions are contained within Services. Create a Service by clicking the Create Service(link takes you to an external page) button and providing a name such as test-function.
  3. Once you've been redirected to the new Service, click the Add + button and select Add Function from the dropdown.
  4. This will create a new Protected Function for you with the option to rename it. The name of the file will be path it is accessed from.
  5. Copy any one of the example code snippets from this page that you want to experiment with, and paste the code into your newly created Function. You can quickly switch examples by using the dropdown menu of the code rail.
  6. Click Save to save your Function's contents.
  7. Click Deploy All to build and deploy the Function. After a short delay, your Function will be accessible from: https://<service-name>-<random-characters>-<optional-domain-suffix>.twil.io/<function-path>
    For example: test-function-3548.twil.io/hello-world.

Your Function is now ready to be invoked by HTTP requests, set as the webhook of a Twilio phone number, invoked by a Twilio Studio Run Function Widget, and more!


Set a Function as a webhook

set-a-function-as-a-webhook page anchor

In order for your Function to react to incoming SMS and/or voice calls, it must be set as a webhook for your Twilio number. There are a variety of methods to set a Function as a webhook, as detailed below:

Twilio ConsoleTwilio CLITwilio SDKs

You can use the Twilio Console(link takes you to an external page) UI as a straightforward way of connecting your Function as a webhook:

  1. Log in to the Twilio Console's Phone Numbers page(link takes you to an external page).

  2. Click on the phone number you'd like to have connected to your Function.

  3. If you want the Function to respond to incoming SMS, find the A Message Comes In option under Messaging. If you want the Function to respond to Voice, find the A Call Comes In option under Voice & Fax.

  4. Select Function from the A Message Comes In or A Call Comes In dropdown.

  5. Select the Service that you are using, then the Environment (this will default to ui unless you have created custom domains ), and finally Function Path of your Function from the respective dropdown menus.
    Connect a Function as a Messaging webhook using the Function dropdowns.
  • Alternatively, you could select Webhook instead of Function, and directly paste in the full URL of the Function.
    Setting a Function as a Messaging webhook using the webhook dropdown option.
  1. Click the Save button.

Respond with a static message

respond-with-a-static-message page anchor

For the most basic possible example, one can reply to the incoming phone call with a hardcoded message. To do so, you can create a new VoiceResponse and declare the intended message contents using the say method. Once your voice content has been set, you can return the generated TwiML by passing it to the callback function as shown and signaling a successful end to the function.

Respond to an incoming phone call

respond-to-an-incoming-phone-call page anchor
1
exports.handler = (context, event, callback) => {
2
// Create a new voice response object
3
const twiml = new Twilio.twiml.VoiceResponse();
4
// Use any of the Node.js SDK methods, such as `say`, to compose a response
5
twiml.say('Ahoy, World!');
6
// Return the TwiML as the second argument to `callback`
7
// This will render the response as XML in reply to the webhook request
8
return callback(null, twiml);
9
};

Respond dynamically to an incoming phone call

respond-dynamically-to-an-incoming-phone-call page anchor

Because information about the incoming phone call is accessible from event object, it's also possible to tailor the response to the call based on that data. For example, you could respond with the city of the caller's phone number, or the number itself. The voice used to respond can also be modified, and pre-recorded audio can be used and/or added as well.

Read the in-depth <Say> documentation for more details about how to configure your response.

Respond dynamically to an incoming phone call

respond-dynamically-to-an-incoming-phone-call-1 page anchor
1
exports.handler = (context, event, callback) => {
2
// Create a new voice response object
3
const twiml = new Twilio.twiml.VoiceResponse();
4
// Webhook information is accessible as properties of the `event` object
5
const city = event.FromCity;
6
const number = event.From;
7
8
// You can optionally edit the voice used, template variables into your
9
// response, play recorded audio, and more
10
twiml.say({ voice: 'alice' }, `Never gonna give you up, ${city || number}`);
11
twiml.play('https://demo.twilio.com/docs/classic.mp3');
12
// Return the TwiML as the second argument to `callback`
13
// This will render the response as XML in reply to the webhook request
14
return callback(null, twiml);
15
};

Forward an incoming phone call

forward-an-incoming-phone-call page anchor

Another common use case is call forwarding. This could be handy in a situation where perhaps you don't want to share your real number while selling an item online, or as part of an IVR tree.

In this example, the Function will accept an incoming phone call and generate a new TwiML response that both notifies the user of the call forwarding and initiates a transfer of the call to the new number.

Read the in-depth <Dial>documentation for more details about connecting calls to other parties.

Forward an incoming phone call

forward-an-incoming-phone-call-1 page anchor
1
const NEW_NUMBER = "+15095550100";
2
3
exports.handler = (context, event, callback) => {
4
// Create a new voice response object
5
const twiml = new Twilio.twiml.VoiceResponse();
6
7
twiml.say('Hello! Forwarding you to our new phone number now!');
8
// The `dial` method will forward the call to the provided E.164 phone number
9
twiml.dial(NEW_NUMBER);
10
// Return the TwiML as the second argument to `callback`
11
// This will render the response as XML in reply to the webhook request
12
return callback(null, twiml);
13
};
(information)

Info

In this example, the number for call forwarding is hardcoded as a string in the Function for convenience. For a more secure approach, consider setting NEW_NUMBER as an Environment Variable in the Functions UI instead. It could then be referenced in your code as context.NEW_NUMBER, as shown in the following example.

Forward an incoming phone call

forward-an-incoming-phone-call-2 page anchor

Use environment variables to store sensitive values

1
exports.handler = (context, event, callback) => {
2
// Create a new voice response object
3
const twiml = new Twilio.twiml.VoiceResponse();
4
// Environment variables that you define can be accessed from `context`
5
const forwardTo = context.NEW_NUMBER;
6
7
twiml.say('Hello! Forwarding you to our new phone number now!');
8
// The `dial` method will forward the call to the provided E.164 phone number
9
twiml.dial(forwardTo);
10
// Return the TwiML as the second argument to `callback`
11
// This will render the response as XML in reply to the webhook request
12
return callback(null, twiml);
13
};

Record an incoming phone call

record-an-incoming-phone-call page anchor

Another common use case would be recording the caller's voice as an audio recording which can be retrieved later. Optionally, you can generate text transcriptions of recorded calls by setting the transcribe attribute of <Record> to true.

Read the in-depth <Record> documentation for more details about recording and/or transcribing calls.

Record an incoming phone call

record-an-incoming-phone-call-1 page anchor
1
exports.handler = (context, event, callback) => {
2
// Create a new voice response object
3
const twiml = new Twilio.twiml.VoiceResponse();
4
5
twiml.say('Hello! Please leave a message after the beep.');
6
// Use <Record> to record the caller's message
7
twiml.record();
8
// End the call with <Hangup>
9
twiml.hangup();
10
// Return the TwiML as the second argument to `callback`
11
// This will render the response as XML in reply to the webhook request
12
return callback(null, twiml);
13
};

Record and transcribe an incoming phone call

record-and-transcribe-an-incoming-phone-call page anchor

Use extra options to configure your recording

1
exports.handler = (context, event, callback) => {
2
// Create a new voice response object
3
const twiml = new Twilio.twiml.VoiceResponse();
4
5
twiml.say('Hello! Please leave a message after the beep.');
6
// Use <Record> to record the caller's message.
7
// Provide options such as `transcribe` to enable message transcription.
8
twiml.record({ transcribe: true });
9
// End the call with <Hangup>
10
twiml.hangup();
11
// Return the TwiML as the second argument to `callback`
12
// This will render the response as XML in reply to the webhook request
13
return callback(null, twiml);
14
};

Creating a moderated conference call

creating-a-moderated-conference-call page anchor

For something more exciting, Functions can also power conference calls. In this example, a "moderator" phone number of your choice will have control of the call in a couple of ways:

  • startConferenceOnEnter will keep all other callers on hold until the moderator joins
  • endConferenceOnExit will cause Twilio to end the call for everyone as soon as the moderator leaves

Incoming calls will be checked based on the incoming event.From value. If it matches the moderator's phone number, the call will begin and then end once the moderator leaves. Any other phone number will join normally and have no effect on the call's beginning or end.

Read the in-depth <Conference> documentation to learn more details.

Create a moderated conference call

create-a-moderated-conference-call page anchor
1
exports.handler = (context, event, callback) => {
2
// Create a new voice response object
3
const twiml = new Twilio.twiml.VoiceResponse();
4
5
// Start with a <Dial> verb
6
const dial = twiml.dial();
7
// If the caller is our MODERATOR, then start the conference when they
8
// join and end the conference when they leave
9
// The MODERATOR phone number MUST be in E.164 format such as "+15095550100"
10
if (event.From === context.MODERATOR) {
11
dial.conference('My conference', {
12
startConferenceOnEnter: true,
13
endConferenceOnExit: true,
14
});
15
} else {
16
// Otherwise have the caller join as a regular participant
17
dial.conference('My conference', {
18
startConferenceOnEnter: false,
19
});
20
}
21
// Return the TwiML as the second argument to `callback`
22
// This will render the response as XML in reply to the webhook request
23
return callback(null, twiml);
24
};

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.