Skip to contentSkip to navigationSkip to topbar
On this page

Secure your Express app by validating incoming Twilio requests


In this guide we'll cover how to secure your Express(link takes you to an external page) application by validating incoming requests to your Twilio webhooks are, in fact, from Twilio.

Securing your Express app with Twilio Node SDK's(link takes you to an external page) is simple. The Twilio SDK comes with an Express middleware which is ready to use.

Let's get started!


Use Twilio Express request validation middleware

use-twilio-express-request-validation-middleware page anchor

The Twilio Node SDK includes a webhook() method which we can use as an Express middleware to validate incoming requests. When applied to an Express route, if the request is unauthorized the middleware will return a 403 HTTP response.

Use Twilio webhook middleware for Express apps that validates Twilio requests

use-twilio-webhook-middleware-for-express-apps-that-validates-twilio-requests page anchor

Confirm incoming requests to your Express routes are genuine with this custom middleware.

1
// You can find your Twilio Auth Token here: https://www.twilio.com/console
2
// Set at runtime as follows:
3
// $ TWILIO_AUTH_TOKEN=XXXXXXXXXXXXXXXXXXX node index.js
4
//
5
// This will not work unless you set the TWILIO_AUTH_TOKEN environment
6
// variable.
7
8
const twilio = require('twilio');
9
const app = require('express')();
10
const bodyParser = require('body-parser');
11
const VoiceResponse = require('twilio').twiml.VoiceResponse;
12
const MessagingResponse = require('twilio').twiml.MessagingResponse;
13
14
app.use(bodyParser.urlencoded({ extended: false }));
15
16
app.post('/voice', twilio.webhook(), (req, res) => {
17
// Twilio Voice URL - receives incoming calls from Twilio
18
const response = new VoiceResponse();
19
20
response.say(
21
`Thanks for calling!
22
Your phone number is ${req.body.From}. I got your call because of Twilio´s
23
webhook. Goodbye!`
24
);
25
26
res.set('Content-Type', 'text/xml');
27
res.send(response.toString());
28
});
29
30
app.post('/message', twilio.webhook(), (req, res) => {
31
// Twilio Messaging URL - receives incoming messages from Twilio
32
const response = new MessagingResponse();
33
34
response.message(`Your text to me was ${req.body.Body.length} characters long.
35
Webhooks are neat :)`);
36
37
res.set('Content-Type', 'text/xml');
38
res.send(response.toString());
39
});
40
41
app.listen(3000);
42

Use a tunnel for your local development environment in order to use live Twilio webhooks

use-a-tunnel-for-your-local-development-environment-in-order-to-use-live-twilio-webhooks page anchor

If your Twilio webhook URLs start with https:// instead of http://, your request validator may fail locally when you use ngrok(link takes you to an external page) or in production if your stack terminates SSL connections upstream from your app. This is because the request URL that your Express application sees does not match the URL Twilio used to reach your application.

To fix this for local development with ngrok, use ngrok http 3000 to accept requests on your webhooks instead of ngrok https 3000.


Disable request validation during testing

disable-request-validation-during-testing page anchor

If you write tests for your Express routes those tests may fail for routes where you use the Twilio request validation middleware. Any requests your test suite sends to those routes will fail the middleware validation check.

To fix this problem we recommend passing {validate: false} to the validation middleware twilio.webhook() thus disabling it. In Express applications it's typical to use NODE_ENV as the value to use to determine the environment the application is running in. In the code example, when NODE_ENV is 'test', the validation middleware should be disabled.

Disable Twilio webhook middleware when testing Express routes.

disable-twilio-webhook-middleware-when-testing-express-routes page anchor

Use environment variable to disable webhook validation during testing.

1
// You can find your Twilio Auth Token here: https://www.twilio.com/console
2
// Set at runtime as follows:
3
// $ TWILIO_AUTH_TOKEN=XXXXXXXXXXXXXXXXXXX node index.js
4
//
5
// This will not work unless you set the TWILIO_AUTH_TOKEN environment
6
// variable.
7
8
const twilio = require('twilio');
9
const app = require('express')();
10
const bodyParser = require('body-parser');
11
const VoiceResponse = require('twilio').twiml.VoiceResponse;
12
const MessagingResponse = require('twilio').twiml.MessagingResponse;
13
14
const shouldValidate = process.env.NODE_ENV !== 'test';
15
16
app.use(bodyParser.urlencoded({ extended: false }));
17
18
app.post('/voice', twilio.webhook({ validate: shouldValidate }), (req, res) => {
19
// Twilio Voice URL - receives incoming calls from Twilio
20
const response = new VoiceResponse();
21
22
response.say(
23
`Thanks for calling!
24
Your phone number is ${req.body.From}. I got your call because of Twilio´s
25
webhook. Goodbye!`
26
);
27
28
res.set('Content-Type', 'text/xml');
29
res.send(response.toString());
30
});
31
32
app.post(
33
'/message',
34
twilio.webhook({ validate: shouldValidate }),
35
(req, res) => {
36
// Twilio Messaging URL - receives incoming messages from Twilio
37
const response = new MessagingResponse();
38
39
response.message(`Your text to me was ${req.body.Body
40
.length} characters long.
41
Webhooks are neat :)`);
42
43
res.set('Content-Type', 'text/xml');
44
res.send(response.toString());
45
}
46
);
47
48
app.listen(3000);
49

Validating requests to your Twilio webhooks is a great first step for securing your Twilio application. We recommend reading over our full security documentation for more advice on protecting your app, and the Anti-Fraud Developer's Guide in particular.

To learn more about securing your Express application in general, check out the security considerations page in the official Express docs.(link takes you to an external page)

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.