This tutorial builds an Express.js webhook that Twilio calls when your number receives an inbound voice call, responding with TwiML instructions that control what the caller hears and where the call goes. It targets Node.js developers who need to program the call experience when someone dials their Twilio number. You will build a route that greets the caller, collects a keypad digit using a Gather verb, and routes the call based on the digit pressed.
Prerequisites and Setup
Install the packages with npm install twilio express dotenv and expose your local server with npx ngrok http 3000. In the Twilio Console, open your phone number's configuration and set the Voice webhook URL to your ngrok HTTPS address followed by /answer, with the HTTP method set to POST. The express.urlencoded({ extended: false }) middleware must be registered before the route so Twilio's form-encoded POST body is parsed correctly. Two routes are needed: one for the main greeting and one for the action that handles the digit the caller presses.
npm install twilio express dotenv
# Twilio Console: Voice webhook
# https://xxxx.ngrok.io/answer (POST)
The Complete Code
The /answer route builds a Gather verb with a numDigits of 1 and an action pointing to /handle-key, which tells Twilio to collect one digit and POST it to the action URL. A say nested inside the Gather plays the menu prompt while waiting for input. The /handle-key route reads req.body.Digits and constructs a Dial verb to connect the caller to the appropriate number. Placing a fallback say after the Gather plays a goodbye message if the caller does not press any digit within the timeout period.
require('dotenv').config();
const express = require('express');
const twilio = require('twilio');
const app = express();
app.use(express.urlencoded({ extended: false }));
const AGENTS = {
'1': '+15550001111',
'2': '+15550002222',
};
app.post('/answer', (req, res) => {
const twiml = new twilio.twiml.VoiceResponse();
const gather = twiml.gather({ numDigits: '1', action: '/handle-key', method: 'POST' });
gather.say({ voice: 'alice' }, 'Press 1 for sales. Press 2 for support.');
twiml.say({ voice: 'alice' }, 'We did not receive your input. Goodbye.');
res.type('text/xml');
res.send(twiml.toString());
});
app.post('/handle-key', (req, res) => {
const digit = req.body.Digits || '';
const twiml = new twilio.twiml.VoiceResponse();
const agentNumber = AGENTS[digit];
if (agentNumber) {
twiml.say({ voice: 'alice' }, 'Connecting you now. Please hold.');
const dial = twiml.dial({ callerId: process.env.TWILIO_PHONE_NUMBER });
dial.number(agentNumber);
} else {
twiml.say({ voice: 'alice' }, 'Invalid selection. Goodbye.');
twiml.hangup();
}
res.type('text/xml');
res.send(twiml.toString());
});
app.listen(3000, () => console.log('Listening on port 3000'));
Testing and Debugging
Call your Twilio number and listen for the greeting to confirm Twilio is reaching your webhook and your Express server is returning valid TwiML. If the call connects but you hear only silence, check that express.urlencoded is registered before the route and that your TwiML contains a Say or Play verb. Twilio error 11200 means your webhook returned a non-2xx status or invalid TwiML; inspect the Twilio Console Call Logs for the exact HTTP response your server returned. Test the timeout fallback by staying silent after the greeting to confirm the fallback message plays instead of the call dropping.
Taking It Further
Add a timeout attribute to the Gather verb to control how many seconds Twilio waits before falling through to the next instruction. Enable speech recognition by adding input: 'speech dtmf' to the Gather options so callers can say department names instead of pressing digits. Log each inbound call and digit selection to a database with the caller's number and timestamp for analytics and quality assurance. Extend the AGENTS map to load from a database or environment variable so routing changes do not require a code deployment.
Contact Telphi Consulting to implement custom inbound call handling with intelligent routing, recording, and CRM integration.
Ready to Transform Your Business Communications?
Get a free consultation with our VoIP experts and discover how we can help you save costs, improve efficiency, and scale your business.
Comments (0)
Join the discussion and share your thoughts (AI-moderated for quality)
Be the first to comment
No comments yet. Share your thoughts below.