Skip to content

Instantly share code, notes, and snippets.

@floriankapaun
Last active May 4, 2022 07:50
Show Gist options
  • Save floriankapaun/4fe0f6e8679def6afc235ce1832e5f33 to your computer and use it in GitHub Desktop.
Save floriankapaun/4fe0f6e8679def6afc235ce1832e5f33 to your computer and use it in GitHub Desktop.

Send Twilio webhook events to multiple destinations using Twilio Functions

Unfortunately, there is currently no way to configure multiple webhook endpoints with Twilio's Console.

As a workaround, we can use Twilio Functions (Pricing) to forward webhook events to multiple destinations.

Setup

Based on Twilio Docs: Receive an inbound SMS

  1. Navigate tho the Functions Tab in your Twilio Console
  2. Create a Service by clicking the Create Service button and entering a name such as forwarding-service
  3. Once you've been redirected to the new Service, click the Add + button and select Add Function from the dropdown menu
  4. Rename the new protected Function if you want -> the name of the file will be path it is accessed from
  5. Copy the attached code snippet, paste it into your newly created Function and click Save to apply your changes
  6. Click on Settings > Dependencies and add axios@latest and querystring@latest
  7. Click Deploy All to build and deploy the Function

After deployment, your Function will be accesible at: https://<service-name>-<random-characters>-<optional-domain-suffix>.twil.io/<function-path>

For example: https://forwarding-service-123456789.twil.io/welcome

const axios = require('axios');
const qs = require('querystring');
exports.handler = function(context, event, callback) {
// Create a new messaging response object
const twiml = new Twilio.twiml.MessagingResponse();
// Specify the URLs to forward the Events to
const url1 = "https://example.com";
const url2 = "https://example.com";
// Setup Content-Type for Requests
const requestOptions = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
// Send requests and await all responses
Promise.all([
axios.post(url1, qs.stringify(event), requestOptions),
axios.post(url2, qs.stringify(event), requestOptions)
])
.then(() => {
callback(null, twiml);
})
.catch(error => {
console.error(error);
callback(error);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment