This tutorial builds a multi-level interactive voice response system using Express.js and Twilio TwiML Gather verbs so callers can navigate a phone menu by pressing keypad digits. It targets Node.js developers who need to route inbound calls through a structured department menu without expensive PBX hardware. You will implement a main menu and department sub-menus with redirect handling and fallback prompts for callers who do not press anything.
Prerequisites and Setup
Install the packages with npm install twilio express dotenv and map out your IVR menu tree before writing any code, since each menu level becomes a pair of Express routes: one for the prompt and one for the digit handler. Expose your local server with npx ngrok http 3000 and configure your Twilio number's voice webhook to POST to /ivr/main. The IVR uses Twilio's Redirect verb to loop callers back to the menu if they do not make a selection within the timeout period. Each handler route reads req.body.Digits and branches to the appropriate next action.
npm install twilio express dotenv
# IVR tree:
# Main: 1 = Sales, 2 = Support, 3 = Billing
# Sales: 1 = New, 2 = Existing
# Support: 1 = Technical, 2 = Account
The Complete Code
Each IVR level is a pair of routes: the menu route builds a Gather with a Say prompt, and the handler route reads the digit and either dials a number, redirects to a sub-menu, or loops back. Placing a redirect after the Gather handles the case where the caller times out without pressing a digit. A shared AGENTS object maps intent keys to phone numbers so routing configuration is separate from TwiML logic. The callerId attribute on the Dial verb ensures the agent sees your Twilio number as the caller ID rather than the original caller's number.
require('dotenv').config();
const express = require('express');
const twilio = require('twilio');
const app = express();
app.use(express.urlencoded({ extended: false }));
const AGENTS = {
sales_new: '+15550001111',
sales_existing: '+15550002222',
support_tech: '+15550003333',
support_acct: '+15550004444',
billing: '+15550005555',
};
function dial(twiml, key) {
twiml.say({ voice: 'alice' }, 'Connecting you now. Please hold.');
const d = twiml.dial({ callerId: process.env.TWILIO_PHONE_NUMBER });
d.number(AGENTS[key]);
}
app.post('/ivr/main', (req, res) => {
const twiml = new twilio.twiml.VoiceResponse();
const g = twiml.gather({ numDigits: '1', action: '/ivr/main-handler', timeout: 5 });
g.say({ voice: 'alice' }, 'Press 1 for sales. Press 2 for support. Press 3 for billing.');
twiml.redirect('/ivr/main');
res.type('text/xml'); res.send(twiml.toString());
});
app.post('/ivr/main-handler', (req, res) => {
const twiml = new twilio.twiml.VoiceResponse();
const d = req.body.Digits;
if (d === '1') twiml.redirect('/ivr/sales');
else if (d === '2') twiml.redirect('/ivr/support');
else if (d === '3') dial(twiml, 'billing');
else { twiml.say({ voice: 'alice' }, 'Invalid option.'); twiml.redirect('/ivr/main'); }
res.type('text/xml'); res.send(twiml.toString());
});
app.post('/ivr/sales', (req, res) => {
const twiml = new twilio.twiml.VoiceResponse();
const g = twiml.gather({ numDigits: '1', action: '/ivr/sales-handler', timeout: 5 });
g.say({ voice: 'alice' }, 'For new accounts press 1. For existing accounts press 2.');
twiml.redirect('/ivr/sales');
res.type('text/xml'); res.send(twiml.toString());
});
app.post('/ivr/sales-handler', (req, res) => {
const twiml = new twilio.twiml.VoiceResponse();
const d = req.body.Digits;
if (d === '1') dial(twiml, 'sales_new');
else if (d === '2') dial(twiml, 'sales_existing');
else twiml.redirect('/ivr/sales');
res.type('text/xml'); res.send(twiml.toString());
});
app.post('/ivr/support', (req, res) => {
const twiml = new twilio.twiml.VoiceResponse();
const g = twiml.gather({ numDigits: '1', action: '/ivr/support-handler', timeout: 5 });
g.say({ voice: 'alice' }, 'For technical support press 1. For account issues press 2.');
twiml.redirect('/ivr/support');
res.type('text/xml'); res.send(twiml.toString());
});
app.post('/ivr/support-handler', (req, res) => {
const twiml = new twilio.twiml.VoiceResponse();
const d = req.body.Digits;
if (d === '1') dial(twiml, 'support_tech');
else if (d === '2') dial(twiml, 'support_acct');
else twiml.redirect('/ivr/support');
res.type('text/xml'); res.send(twiml.toString());
});
app.listen(3000, () => console.log('IVR listening on port 3000'));
Testing and Debugging
Call your Twilio number and navigate each branch of the menu to confirm every digit maps to the correct next action. Test the timeout fallback by staying silent after each prompt to confirm the redirect loops back to the same menu rather than dropping the call. Use the Twilio Console Call Logs to trace the exact sequence of TwiML fetches, HTTP statuses, and verb executions during each test call. If a redirect results in an infinite loop, check that the redirect target route is registered in Express and returns a valid non-redirect TwiML response at some point in the flow.
Taking It Further
Load the menu structure and agent numbers from a database or JSON configuration file so operations staff can update routing without touching Node.js code. Add time-based routing in each handler using new Date() and a timezone library to redirect after-hours calls to a voicemail route automatically. Replace the Say prompts with Play verbs using pre-recorded MP3 audio files for a more professional caller experience. Enable speech input by setting input: 'speech dtmf' on each Gather so callers can say department names as an alternative to pressing digits.
Contact Telphi Consulting to architect and deploy a production IVR with analytics, recording, and CRM integration built in.
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.