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.
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.
If you prefer a UI-driven approach, complete these steps in the Twilio Console:
- Log in to the Twilio Console and navigate to Develop > Functions & Assets. If you're using the legacy Console, open the Functions tab.
- Functions are contained within Services. Click Create Service to create a new Service.
- Click Add + and select Add Function from the dropdown.
- The Console creates a new protected Function that you can rename. The filename becomes the URL path of the Function.
- 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.
- Click Save.
- 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.
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:
Use the Twilio Console UI to connect your Function as a webhook:
- Go to Products & Services > Numbers & Senders > Phone Numbers.
- Select the phone number you'd like to connect to your Function.
- 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.
- Select the webhook method and provide your webhook URL. Select an HTTP method to handle responses.
- Optional: Configure a secondary webhook in case the primary webhook fails.
- Click the Save button.
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.
1exports.handler = (context, event, callback) => {2// Create a new voice response object3const twiml = new Twilio.twiml.VoiceResponse();4// Use any of the Node.js SDK methods, such as `say`, to compose a response5twiml.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 request8return callback(null, twiml);9};
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.
1exports.handler = (context, event, callback) => {2// Create a new voice response object3const twiml = new Twilio.twiml.VoiceResponse();4// Webhook information is accessible as properties of the `event` object5const city = event.FromCity;6const number = event.From;78// You can optionally edit the voice used, template variables into your9// response, play recorded audio, and more10twiml.say({ voice: 'alice' }, `Never gonna give you up, ${city || number}`);11twiml.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 request14return callback(null, twiml);15};
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.
1const NEW_NUMBER = "+15095550100";23exports.handler = (context, event, callback) => {4// Create a new voice response object5const twiml = new Twilio.twiml.VoiceResponse();67twiml.say('Hello! Forwarding you to our new phone number now!');8// The `dial` method will forward the call to the provided E.164 phone number9twiml.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 request12return callback(null, twiml);13};
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.
Use environment variables to store sensitive values
1exports.handler = (context, event, callback) => {2// Create a new voice response object3const twiml = new Twilio.twiml.VoiceResponse();4// Environment variables that you define can be accessed from `context`5const forwardTo = context.NEW_NUMBER;67twiml.say('Hello! Forwarding you to our new phone number now!');8// The `dial` method will forward the call to the provided E.164 phone number9twiml.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 request12return callback(null, twiml);13};
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.
1exports.handler = (context, event, callback) => {2// Create a new voice response object3const twiml = new Twilio.twiml.VoiceResponse();45twiml.say('Hello! Please leave a message after the beep.');6// Use <Record> to record the caller's message7twiml.record();8// End the call with <Hangup>9twiml.hangup();10// Return the TwiML as the second argument to `callback`11// This will render the response as XML in reply to the webhook request12return callback(null, twiml);13};
Use extra options to configure your recording
1exports.handler = (context, event, callback) => {2// Create a new voice response object3const twiml = new Twilio.twiml.VoiceResponse();45twiml.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.8twiml.record({ transcribe: true });9// End the call with <Hangup>10twiml.hangup();11// Return the TwiML as the second argument to `callback`12// This will render the response as XML in reply to the webhook request13return callback(null, twiml);14};
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.
1exports.handler = (context, event, callback) => {2// Create a new voice response object3const twiml = new Twilio.twiml.VoiceResponse();45// Start with a <Dial> verb6const dial = twiml.dial();7// If the caller is our MODERATOR, then start the conference when they8// join and end the conference when they leave9// The MODERATOR phone number MUST be in E.164 format such as "+15095550100"10if (event.From === context.MODERATOR) {11dial.conference('My conference', {12startConferenceOnEnter: true,13endConferenceOnExit: true,14});15} else {16// Otherwise have the caller join as a regular participant17dial.conference('My conference', {18startConferenceOnEnter: 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 request23return callback(null, twiml);24};

