How to use the Twilio Taskrouter SDK in a Flex Plugin

Twilio Flex Plugins offer an easy and customizable way to add additional functionality and features to your Twilio Flex environment. Flex plugins are very powerful as they help deliver exact solutions to your customers needs.

The Flex manager and the Twilio functions are accessible inside our flex plugin where the flex manager gives us read only access to the Twilio SDK in a limited capacity. What this means is that the full Twilio SDK is not available inside our Flex plugin but fear not there is a way around this!

I will guide you through my specific example on how I was able to access the associated HTTP headers for my Twilio taskrouter task but the concept will apply to anything you would like to access in the Twilio SDK. The trick is to leverage Twilio functions which are serverless code snippets we can use to access and return whatever we want from the Twilio SDK. Let’s run through an example to understand this better.

I am making an assumption that you have successfully deployed a Twilio Flex environment and have worked with Twilio functions before, if not refer to these links these here: 1 & 2. My goal here is to access the HTTP headers associated with my task but the Flex manager doesn’t provide me with any way to do that. So I will create a new Twilio function that is responsible for retrieving the HTTP headers for my task, my Twilio flex plugin will now be able to talk to the Twilio function and access whatever it needs in the Twilio SDK (the HTTP headers in this case.).

const Twilio = require('twilio');exports.handler = TokenValidator(async function(context, event, callback) {const twilioClient = context.getTwilioClient();const response = new Twilio.Response();const task = await twilioClient.taskrouter.workspaces(workspaceSid) //Will need to pass in the workspaceSid.tasks(taskSid) //Will need to pass in the taskSid.fetch()console.log(task);//Assigning response to the headers of the last request.
response = twilioClient._httpClient.lastResponse.headers
callback(null, response);});

You might be wondering how do I actually use the SDK in the Twilio function? Fortunately it is a fairly easy process, since your function already sits inside your Twilio instance you can simply use the context.getTwilioClient() function to initialize the client to use the SDK. Now you can assign a variable to the above function and access the SDK using this variable. The only thing left now is to return whatever value your flex plugin wants inside the Twilio function and call this function inside the flex plugin. Just like that you are now accessing the full Twilio SDK in your flex plugin!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store