# 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

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](/docs/labs/serverless-toolkit).

## Console

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

1. Log in to the [Twilio Console](https://1console.twilio.com) and navigate to **Develop > Functions & Assets**. If you're using the *legacy* Console, open the [**Functions** tab](https://www.twilio.com/console/functions/overview).
2. Functions are contained within **Services**. Click **[Create Service](https://www.twilio.com/console/functions/overview/services)** to create a new **[Service](/docs/serverless/functions-assets/functions/create-service)**.
3. Click **Add +** and select **Add Function** from the dropdown.
4. The Console creates a new [protected](/docs/serverless/functions-assets/visibility) 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`.

## Serverless Toolkit

The [Serverless Toolkit](/docs/labs/serverless-toolkit) lets you develop locally, deploy projects, and perform other tasks through the [Twilio CLI](/docs/twilio-cli/quickstart).

1. From the CLI, run `twilio serverless:init <YOUR-SERVICE-NAME> --empty` to bootstrap your local environment.
2. Go to your new project directory using `cd <YOUR-SERVICE-NAME>`.
3. In the `/functions` directory, create a JavaScript file whose name reflects 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. Add the code example of your choice to the file and save it. Note that a Function can only export a single handler. You need to create separate files to run or deploy multiple examples at once.

After you save the Function code, you can test it locally (and optionally tunnel requests to it using a tool like [ngrok](https://ngrok.com/)), or deploy it.

### Run your Function in local development

Run `twilio serverless:start` from your CLI to start the project locally. The Function(s) in your project are 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 automatically generates 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 to test with [Twilio Voice](/docs/voice).
* If your code does *not* connect to Twilio Voice or Messages as a webhook, 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 deploys 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`

You can now invoke your Function with HTTP requests, configure it as the [webhook](/docs/usage/webhooks/getting-started-twilio-webhooks) for a Twilio phone number, call it from a Twilio Studio [**Run Function** Widget](/docs/studio/widget-library/run-function), and more.

## Set a Function as a webhook

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

![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);
};
```
