The following documentation is for the JS SDK V1. If you're working with the Twilio Flex SDK, head over to the TaskRouter.js documentation on Github.
The SDK allows developers to interact with the entire TaskRouter REST API by a simple JS API.
Include the TaskRouter JS SDK in your JavaScript application as follows:
<script src="https://sdk.twilio.com/js/taskrouter/v1.21/taskrouter.min.js" integrity="sha384-5fq+0qjayReAreRyHy38VpD3Gr9R2OYIzonwIkoGI4M9dhfKW6RWeRnZjfwSrpN8" crossorigin="anonymous"></script>
TaskRouter uses Twilio capability tokens to delegate scoped access to TaskRouter resources to your JavaScript application. Twilio capability tokens conform to the JSON Web Token (commonly referred to as a JWT and pronounced "jot") standard, which allow for limited-time use of credentials by a third party. Your web server needs to generate a Twilio capability token and provide it to your JavaScript application in order to register a TaskRouter TaskQueue.
We provide three relevant helper methods to provide access capabilities:
Capability | Authorization |
---|---|
AllowFetchSubresources | A TaskQueue can fetch any subresource (statistics) |
AllowUpdates | A TaskQueue can update its properties |
AllowDelete | A TaskQueue can delete itself |
Additionally, you can utilize more granular access to particular resources beyond these capabilities. These can viewed under Constructing JWTs.
You can generate a TaskRouter capability token using any of Twilio's Helper Libraries. You'll need to provide your Twilio AccountSid and AuthToken, the WorkspaceSid the TaskQueue belongs to and the TaskQueueSid you would like to register. For example, using our PHP helper library you can create a token and add capabilities as follows:
1// Download the Node helper library from twilio.com/docs/node/install2// These consts are your accountSid and authToken from https://www.twilio.com/console3const taskrouter = require('twilio').jwt.taskrouter;45const TaskRouterCapability = taskrouter.TaskRouterCapability;6const Policy = TaskRouterCapability.Policy;78// To set up environmental variables, see http://twil.io/secure9const accountSid = process.env.TWILIO_ACCOUNT_SID;10const authToken = process.env.TWILIO_AUTH_TOKEN;11const workspaceSid = 'WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';12const taskqueueSid = 'WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';1314const TASKROUTER_BASE_URL = 'https://taskrouter.twilio.com';15const version = 'v1';1617// By default, tokens are good for one hour.18// Override this default timeout by specifiying a new value (in seconds).19// For example, to generate a token good for 8 hours:20const ttl = 28800; // 60 * 60 * 82122const capability = new TaskRouterCapability({23accountSid: accountSid,24authToken: authToken,25workspaceSid: workspaceSid,26channelId: taskqueueSid,27ttl: ttl,28});2930// Helper function to create Policy31function buildWorkspacePolicy(options) {32options = options || {};33const resources = options.resources || [];34const urlComponents = [35TASKROUTER_BASE_URL,36version,37'Workspaces',38workspaceSid,39];4041return new Policy({42url: urlComponents.concat(resources).join('/'),43method: options.method || 'GET',44allow: true,45});46}4748const allowFetchSubresources = buildWorkspacePolicy({49resources: ['TaskQueue', taskqueueSid, '**']50});51const allowUpdates = buildWorkspacePolicy({52resources: ['TaskQueue', taskqueueSid],53method: 'POST',54});5556capability.addPolicy(allowFetchSubresources);57capability.addPolicy(allowUpdates);5859const token = capability.toJwt();
Once you have generated a TaskRouter capability token, you can pass this to your front-end web application and initialize the JavaScript library as follows:
var taskQueue = new Twilio.TaskRouter.TaskQueue(TASKQUEUE_TOKEN);
The library will raise a 'ready' event once it has connected to TaskRouter:
1taskQueue.on("ready", function(taskQueue) {2console.log(taskQueue.sid) // 'WQxxx'3console.log(taskQueue.friendlyName) // 'Simple FIFO Queue'4console.log(taskQueue.targetWorkers) // '1==1'5console.log(taskQueue.maxReservedWorkers) // 206});
See more about the methods and events exposed on this object below.
TaskRouter.js TaskQueue exposes the following API:
Twilio.TaskRouter.TaskQueue is the top-level class you'll use for managing a TaskQueue.
Register a new Twilio.TaskRouter.TaskQueue with the capabilities provided in taskQueueToken
.
Name | Type | Description |
---|---|---|
taskQueueToken | String | A Twilio TaskRouter capability token. See Creating a TaskRouter capability token for more information. |
debug | Boolean | (optional) Whether or not the JS SDK will print event messages to the console. Defaults to true. |
region | String | (optional) A Twilio region for websocket connections (ex. ie1-ix ). |
maxRetries | Integer | (optional) The maximum of retries to attempt if a websocket request fails. Defaults to 0. |
var taskQueue = new Twilio.TaskRouter.TaskQueue(TASKQUEUE_TOKEN);
Turning off debugging:
var taskQueue = new Twilio.TaskRouter.TaskQueue(TASKQUEUE_TOKEN, false);
Updates a single or list of properties on a TaskQueue.
Name | Type | Description |
---|---|---|
args... | String or JSON | A single API parameter and value or a JSON object containing multiple values |
resultCallback | Function | (optional) A JavaScript Function that will be called with the result of the update. If an error occurs, the first argument passed to this function will be an Error. If the update is successful, the first argument will be null and the second argument will contain the updated TaskQueue. |
1taskQueue.update("MaxReservedWorkers", "20", function(error, taskQueue) {2if(error) {3console.log(error.code);4console.log(error.message);5} else {6console.log(taskQueue.maxReservedWorkers); // 207}8});
1var targetWorkers = "languages HAS \"english\"";2var props = {"MaxReservedWorkers", "20", "TargetWorkers":targetWorkers};3taskQueue.update(props, function(error, workspace) {4if(error) {5console.log(error.code);6console.log(error.message);7} else {8console.log(taskQueue.maxReservedWorkers); // "20"9console.log(taskQueue.targetWorkers); // "languages HAS "english""10}11});
Deletes a TaskQueue
Name | Type | Description |
---|---|---|
resultCallback | Function | (optional) A JavaScript Function that will be called with the result of the delete. If an error occurs, the first argument passed to this function will be an Error. If the delete is successful, the first argument will be null. |
1taskQueue.delete(function(error) {2if(error) {3console.log(error.code);4console.log(error.message);5} else {6console.log("taskQueue deleted");7}8});
Updates the TaskRouter capability token for the Workspace.
Name | Type | Description |
---|---|---|
taskQueueToken | String | A valid TaskRouter capability token. |
1var token = refreshJWT(); // your method to retrieve a new capability token2taskQueue.updateToken(token);
Retrieves the object to retrieve the statistics for a TaskQueue.
Name | Type | Description |
---|---|---|
params | JSON | (optional) A JSON object of query parameters |
callback | Function | A function that will be called when the statistics object is returned. If an error occurs when retrieving the list, the first parameter passed to this function will contain the Error object. If the retrieval is successful, the first parameter will be null and the second parameter will contain a statistics object. |
1var queryParams = {"Minutes":"240"}; // 4 hours2taskQueue.statistics.fetch(3queryParams,4function(error, statistics) {5if(error) {6console.log(error.code);7console.log(error.message);8return;9}10console.log("fetched taskQueue statistics: "+JSON.stringify(statistics));11console.log("avg task acceptance time: "+statistics.cumulative.avgTaskAcceptanceTime;12}13);
If you only care about the cumulative stats for a TaskQueue for a given time period, you can utilize this instead of the above for a smaller payload and faster response time.
Name | Type | Description |
---|---|---|
params | JSON | (optional) A JSON object of query parameters |
callback | Function | A function that will be called when the statistics object is returned. If an error occurs when retrieving the list, the first parameter passed to this function will contain the Error object. If the retrieval is successful, the first parameter will be null and the second parameter will contain a statistics object. |
1var queryParams = {"Minutes":"240"}; // 4 hours2taskQueue.cumulativeStats.fetch(3queryParams,4function(error, statistics) {5if(error) {6console.log(error.code);7console.log(error.message);8return;9}10console.log("fetched taskQueue statistics: "+JSON.stringify(statistics));11console.log("avg task acceptance time: "+statistics.avgTaskAcceptanceTime;12}13);
If you only care about the realtime stats for a TaskQueue for a given time period, you can utilize this instead of the above for a smaller payload and faster response time.
Name | Type | Description |
---|---|---|
params | JSON | (optional) A JSON object of query parameters |
callback | Function | A function that will be called when the statistics object is returned. If an error occurs when retrieving the list, the first parameter passed to this function will contain the Error object. If the retrieval is successful, the first parameter will be null and the second parameter will contain a statistics object. |
1taskQueue.realtimeStats.fetch(2function(error, statistics) {3if(error) {4console.log(error.code);5console.log(error.message);6return;7}8console.log("fetched taskQueue statistics: "+JSON.stringify(statistics));9console.log("total available workers: "+statistics.totalAvailableWorkers;10console.log("total eligible workers: "+statistics.totalEligibleWorkers;11}12);
Attaches a listener to the specified event. See Events for the complete list of supported events.
Name | Type | Description |
---|---|---|
event | String | An event name. See Events for the complete list of supported events. |
callback | Function | A function that will be called when the specified Event is raised. |
1taskQueue.on("ready", function(taskQueue) {2console.log(taskQueue.friendlyName) // My TaskQueue3});
TaskRouter's JS library currently raises the following events to the registered TaskQueue:
The TaskQueue has established a connection to TaskRouter and has completed initialization.
Name | Type | Description |
---|---|---|
taskQueue | TaskQueue | The created TaskQueue. |
1taskQueue.on("ready", function(taskQueue) {2console.log(taskQueue.friendlyName) // My TaskQueue3});
The TaskQueue has established a connection to TaskRouter.
1taskQueue.on("connected", function() {2console.log("Websocket has connected");3});
The TaskQueue has disconnected a connection from TaskRouter.
1taskQueue.on("disconnected", function() {2console.log("Websocket has disconnected");3});
Raised when the TaskRouter capability token used to create this TaskQueue expires.
1taskQueue.on("token.expired", function() {2console.log("updating token");3var token = refreshJWT(); // your method to retrieve a new capability token4taskQueue.updateToken(token);5});