# 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](/docs/voice/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](/docs/voice/twiml#twilios-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

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](/docs/labs/serverless-toolkit) as explained below:

## Console

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](https://www.twilio.com/console/functions/overview). If you need an account, you can sign up for a free Twilio account [here](https://www.twilio.com/try-twilio)!
2. Functions are contained within **Services**. Create a **[Service](/docs/serverless/functions-assets/functions/create-service)** by clicking the **[Create Service](https://www.twilio.com/console/functions/overview/services)** 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](/docs/serverless/functions-assets/visibility) 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`.

## Serverless Toolkit

The [Serverless Toolkit](/docs/labs/serverless-toolkit) enables you with local development, project deployment, and other functionality via the [Twilio CLI](/docs/twilio-cli/quickstart). To get up and running with these examples using Serverless Toolkit, follow this process:

1. From the CLI, run `twilio serverless:init <your-service-name> --empty` to bootstrap your local environment.
2. Navigate into your new project directory using `cd <your-service-name>`
3. In the `/functions` directory, create a new JavaScript file that is named respective to the purpose of the Function. For example, `sms-reply.protected.js` for a [Protected](/docs/serverless/functions-assets/visibility) Function intended to handle incoming SMS.
4. Populate the file using the code example of your choice and save. **Note** A Function can only export a single handler. You will want to create separate files if you want to run and/or deploy multiple examples at once.

Once your Function(s) code is written and saved, you can test it either by running it locally (and optionally tunneling requests to it via a tool like [ngrok](https://ngrok.com/)), or by deploying the Function and executing against the deployed url(s).

### Run your Function in local development

Run `twilio serverless:start` from your CLI to start the project locally. The Function(s) in your project will be accessible from `http://localhost:3000/sms-reply`

* If you want to test a Function as a [Twilio webhook](/docs/usage/webhooks/getting-started-twilio-webhooks), run: `twilio phone-numbers:update <your Twilio phone number> --sms-url "http://localhost:3000/sms-reply"`\
  This will automatically generate an ngrok tunnel from Twilio to your locally running Function, so you can start sending texts to it. You can apply the same process but with the `voice-url` flag instead if you want to test with [Twilio Voice](/docs/voice).
* If your code does *not* connect to Twilio Voice/Messages as a webhook, you can start your dev server and start an ngrok tunnel in the same command with the `ngrok` flag. For example: `twilio serverless:start --ngrok=""`

### Deploy your Function

To deploy your Function and have access to live url(s), run `twilio serverless:deploy` from your CLI. This will deploy your Function(s) to Twilio under a development environment by default, where they can be accessed from:

`https://<service-name>-<random-characters>-dev.twil.io/<function-path>`

For example: `https://incoming-sms-examples-3421-dev.twil.io/sms-reply`

Your Function is now ready to be invoked by HTTP requests, set as the [webhook](/docs/usage/webhooks/getting-started-twilio-webhooks) of a Twilio phone number, invoked by a Twilio Studio **[Run Function Widget](/docs/studio/widget-library/run-function)**, and more!

## Set a Function as a webhook

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

![Setting a Function as a Messaging webhook using the webhook dropdown option.](https://docs-resources.prod.twilio.com/bf4eae4ac40fe7d47003a93bca295d5c232e0b372358e73ceff931fee3ccdc4f.png)

## Respond with a static message

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.

```js title="Respond to an incoming phone call"
exports.handler = (context, event, callback) => {
  // Create a new voice response object
  const twiml = new Twilio.twiml.VoiceResponse();
  // Use any of the Node.js SDK methods, such as `say`, to compose a response
  twiml.say('Ahoy, World!');
  // Return the TwiML as the second argument to `callback`
  // This will render the response as XML in reply to the webhook request
  return callback(null, twiml);
};
```

## Respond dynamically to an incoming phone call

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](/docs/voice/twiml/say) for more details about how to configure your response.

```js title="Respond dynamically to an incoming phone call"
exports.handler = (context, event, callback) => {
  // Create a new voice response object
  const twiml = new Twilio.twiml.VoiceResponse();
  // Webhook information is accessible as properties of the `event` object
  const city = event.FromCity;
  const number = event.From;

  // You can optionally edit the voice used, template variables into your
  // response, play recorded audio, and more
  twiml.say({ voice: 'alice' }, `Never gonna give you up, ${city || number}`);
  twiml.play('https://demo.twilio.com/docs/classic.mp3');
  // Return the TwiML as the second argument to `callback`
  // This will render the response as XML in reply to the webhook request
  return callback(null, twiml);
};
```

## Forward an incoming phone call

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](/docs/glossary/what-is-ivr).

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>](/docs/voice/twiml/dial)[documentation](/docs/voice/twiml/dial) for more details about connecting calls to other parties.

```js title="Forward an incoming phone call"
const NEW_NUMBER = "+15095550100";

exports.handler = (context, event, callback) => {
  // Create a new voice response object
  const twiml = new Twilio.twiml.VoiceResponse();

  twiml.say('Hello! Forwarding you to our new phone number now!');
  // The `dial` method will forward the call to the provided E.164 phone number
  twiml.dial(NEW_NUMBER);
  // Return the TwiML as the second argument to `callback`
  // This will render the response as XML in reply to the webhook request
  return callback(null, twiml);
};
```

> \[!NOTE]
>
> 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](/docs/serverless/functions-assets/functions)** in the Functions UI instead. It could then be referenced in your code as `context.NEW_NUMBER`, as shown in the following example.

```js title="Forward an incoming phone call" description="Use environment variables to store sensitive values"
exports.handler = (context, event, callback) => {
  // Create a new voice response object
  const twiml = new Twilio.twiml.VoiceResponse();
  // Environment variables that you define can be accessed from `context`
  const forwardTo = context.NEW_NUMBER;

  twiml.say('Hello! Forwarding you to our new phone number now!');
  // The `dial` method will forward the call to the provided E.164 phone number
  twiml.dial(forwardTo);
  // Return the TwiML as the second argument to `callback`
  // This will render the response as XML in reply to the webhook request
  return callback(null, twiml);
};
```

## Record an incoming phone call

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](/docs/voice/twiml/record) for more details about recording and/or transcribing calls.

```js title="Record an incoming phone call"
exports.handler = (context, event, callback) => {
  // Create a new voice response object
  const twiml = new Twilio.twiml.VoiceResponse();

  twiml.say('Hello! Please leave a message after the beep.');
  // Use <Record> to record the caller's message
  twiml.record();
  // End the call with <Hangup>
  twiml.hangup();
  // Return the TwiML as the second argument to `callback`
  // This will render the response as XML in reply to the webhook request
  return callback(null, twiml);
};
```

```js title="Record and transcribe an incoming phone call" description="Use extra options to configure your recording"
exports.handler = (context, event, callback) => {
  // Create a new voice response object
  const twiml = new Twilio.twiml.VoiceResponse();

  twiml.say('Hello! Please leave a message after the beep.');
  // Use <Record> to record the caller's message.
  // Provide options such as `transcribe` to enable message transcription.
  twiml.record({ transcribe: true });
  // End the call with <Hangup>
  twiml.hangup();
  // Return the TwiML as the second argument to `callback`
  // This will render the response as XML in reply to the webhook request
  return callback(null, twiml);
};
```

## Creating a moderated conference call

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](/docs/voice/twiml/conference) to learn more details.

```js title="Create a moderated conference call"
exports.handler = (context, event, callback) => {
  // Create a new voice response object
  const twiml = new Twilio.twiml.VoiceResponse();

  // Start with a <Dial> verb
  const dial = twiml.dial();
  // If the caller is our MODERATOR, then start the conference when they
  // join and end the conference when they leave
  // The MODERATOR phone number MUST be in E.164 format such as "+15095550100"
  if (event.From === context.MODERATOR) {
    dial.conference('My conference', {
      startConferenceOnEnter: true,
      endConferenceOnExit: true,
    });
  } else {
    // Otherwise have the caller join as a regular participant
    dial.conference('My conference', {
      startConferenceOnEnter: false,
    });
  }
  // Return the TwiML as the second argument to `callback`
  // This will render the response as XML in reply to the webhook request
  return callback(null, twiml);
};
```
