Skip to contentSkip to navigationSkip to topbar
Page toolsOn this page
Looking for more inspiration?Visit the

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

Before you run any of the examples on this page, create a Function and paste the example code into it. You can create a Function in the Twilio Console or by using the Serverless Toolkit.

ConsoleServerless Toolkit

If you prefer a UI-driven approach, complete these steps in the Twilio Console:

  1. Log in to the Twilio Console(link takes you to an external page) and navigate to Develop > Functions & Assets. If you're using the legacy Console, open the Functions tab(link takes you to an external page).
  2. Functions are contained within Services. Click Create Service(link takes you to an external page) to create a new Service.
  3. Click Add + and select Add Function from the dropdown.
  4. The Console creates a new protected Function that you can rename. The filename becomes the URL path of the Function.
  5. Copy one of the example code snippets from this page and paste the code into your newly created Function. You can switch examples by using the dropdown menu in the code rail.
  6. Click Save.
  7. Click Deploy All to build and deploy the Function. After deployment, you can access your Function at https://<service-name>-<random-characters>-<optional-domain-suffix>.twil.io/<function-path>
    For example: test-function-3548.twil.io/hello-world.

You can now invoke your Function with HTTP requests, configure it as the webhook for a Twilio phone number, call it from a Twilio Studio Run Function Widget, and more.


Set a Function as a webhook

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

For your Function to react to incoming SMS 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:

Twilio ConsoleLegacy Twilio ConsoleTwilio CLITwilio server-side SDKs

Use the Twilio Console(link takes you to an external page) UI to connect your Function as a webhook:

  1. Go to Products & Services > Numbers & Senders > Phone Numbers.
  2. Select the phone number you'd like to connect to your Function.
  3. Go to the Configuration Details tab.
  • To configure Messaging, choose Edit details in the Messaging section.
  • To configure Voice calls, choose Edit details in the Voice and emergency calling section.
  1. Select the webhook method and provide your webhook URL. Select an HTTP method to handle responses.
  2. Optional: Configure a secondary webhook in case the primary webhook fails.
  3. 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
};