Skip to contentSkip to navigationSkip to topbar
On this page

TaskRouter.js v1 TaskQueue: Managing a TaskQueue resource in the browser


(information)

Info

The following documentation is for the JS SDK V1(link takes you to an external page). If you're working with the Twilio Flex SDK, head over to the TaskRouter.js documentation on Github(link takes you to an external page).

The SDK allows developers to interact with the entire TaskRouter REST API by a simple JS API.


Adding the SDK to your application

adding-the-sdk-to-your-application page anchor

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>

Creating a TaskRouter TaskQueue capability token

capability-token page anchor

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:

CapabilityAuthorization
AllowFetchSubresourcesA TaskQueue can fetch any subresource (statistics)
AllowUpdatesA TaskQueue can update its properties
AllowDeleteA 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:

Creating a TaskRouter TaskQueue capability tokenLink to code sample: Creating a TaskRouter TaskQueue capability token
1
// Download the Node helper library from twilio.com/docs/node/install
2
// These consts are your accountSid and authToken from https://www.twilio.com/console
3
const taskrouter = require('twilio').jwt.taskrouter;
4
5
const TaskRouterCapability = taskrouter.TaskRouterCapability;
6
const Policy = TaskRouterCapability.Policy;
7
8
// To set up environmental variables, see http://twil.io/secure
9
const accountSid = process.env.TWILIO_ACCOUNT_SID;
10
const authToken = process.env.TWILIO_AUTH_TOKEN;
11
const workspaceSid = 'WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
12
const taskqueueSid = 'WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
13
14
const TASKROUTER_BASE_URL = 'https://taskrouter.twilio.com';
15
const version = 'v1';
16
17
// 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:
20
const ttl = 28800; // 60 * 60 * 8
21
22
const capability = new TaskRouterCapability({
23
accountSid: accountSid,
24
authToken: authToken,
25
workspaceSid: workspaceSid,
26
channelId: taskqueueSid,
27
ttl: ttl,
28
});
29
30
// Helper function to create Policy
31
function buildWorkspacePolicy(options) {
32
options = options || {};
33
const resources = options.resources || [];
34
const urlComponents = [
35
TASKROUTER_BASE_URL,
36
version,
37
'Workspaces',
38
workspaceSid,
39
];
40
41
return new Policy({
42
url: urlComponents.concat(resources).join('/'),
43
method: options.method || 'GET',
44
allow: true,
45
});
46
}
47
48
const allowFetchSubresources = buildWorkspacePolicy({
49
resources: ['TaskQueue', taskqueueSid, '**']
50
});
51
const allowUpdates = buildWorkspacePolicy({
52
resources: ['TaskQueue', taskqueueSid],
53
method: 'POST',
54
});
55
56
capability.addPolicy(allowFetchSubresources);
57
capability.addPolicy(allowUpdates);
58
59
const 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:

1
taskQueue.on("ready", function(taskQueue) {
2
console.log(taskQueue.sid) // 'WQxxx'
3
console.log(taskQueue.friendlyName) // 'Simple FIFO Queue'
4
console.log(taskQueue.targetWorkers) // '1==1'
5
console.log(taskQueue.maxReservedWorkers) // 20
6
});

See more about the methods and events exposed on this object below.


TaskRouter.js TaskQueue exposes the following API:


Twilio.TaskRouter.TaskQueue

taskroutertaskqueue page anchor

Twilio.TaskRouter.TaskQueue is the top-level class you'll use for managing a TaskQueue.

new Twilio.TaskRouter.TaskQueue(taskQueueToken)

new-taskroutertaskqueue page anchor

Register a new Twilio.TaskRouter.TaskQueue with the capabilities provided in taskQueueToken.

Parameters

parameters page anchor
NameTypeDescription
taskQueueTokenStringA Twilio TaskRouter capability token. See Creating a TaskRouter capability token for more information.
debugBoolean(optional) Whether or not the JS SDK will print event messages to the console. Defaults to true.
regionString(optional) A Twilio region for websocket connections (ex. ie1-ix).
maxRetriesInteger(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);

update([args...], [resultCallback])

update page anchor

Updates a single or list of properties on a TaskQueue.

NameTypeDescription
args...String or JSONA single API parameter and value or a JSON object containing multiple values
resultCallbackFunction(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.
Single Attribute Example
single-attribute-example page anchor
1
taskQueue.update("MaxReservedWorkers", "20", function(error, taskQueue) {
2
if(error) {
3
console.log(error.code);
4
console.log(error.message);
5
} else {
6
console.log(taskQueue.maxReservedWorkers); // 20
7
}
8
});
Multiple Attribute Example
multiple-attribute-example page anchor
1
var targetWorkers = "languages HAS \"english\"";
2
var props = {"MaxReservedWorkers", "20", "TargetWorkers":targetWorkers};
3
taskQueue.update(props, function(error, workspace) {
4
if(error) {
5
console.log(error.code);
6
console.log(error.message);
7
} else {
8
console.log(taskQueue.maxReservedWorkers); // "20"
9
console.log(taskQueue.targetWorkers); // "languages HAS "english""
10
}
11
});

delete([resultCallback])

delete page anchor

Deletes a TaskQueue

NameTypeDescription
resultCallbackFunction(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.
1
taskQueue.delete(function(error) {
2
if(error) {
3
console.log(error.code);
4
console.log(error.message);
5
} else {
6
console.log("taskQueue deleted");
7
}
8
});

updateToken(taskQueueToken)

updatetoken page anchor

Updates the TaskRouter capability token for the Workspace.

NameTypeDescription
taskQueueTokenStringA valid TaskRouter capability token.
1
var token = refreshJWT(); // your method to retrieve a new capability token
2
taskQueue.updateToken(token);

Retrieves the object to retrieve the statistics for a TaskQueue.

NameTypeDescription
paramsJSON(optional) A JSON object of query parameters
callbackFunctionA 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.
1
var queryParams = {"Minutes":"240"}; // 4 hours
2
taskQueue.statistics.fetch(
3
queryParams,
4
function(error, statistics) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
console.log("fetched taskQueue statistics: "+JSON.stringify(statistics));
11
console.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.

NameTypeDescription
paramsJSON(optional) A JSON object of query parameters
callbackFunctionA 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.
1
var queryParams = {"Minutes":"240"}; // 4 hours
2
taskQueue.cumulativeStats.fetch(
3
queryParams,
4
function(error, statistics) {
5
if(error) {
6
console.log(error.code);
7
console.log(error.message);
8
return;
9
}
10
console.log("fetched taskQueue statistics: "+JSON.stringify(statistics));
11
console.log("avg task acceptance time: "+statistics.avgTaskAcceptanceTime;
12
}
13
);

real time statistics

realtimestatistics page anchor

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.

NameTypeDescription
paramsJSON(optional) A JSON object of query parameters
callbackFunctionA 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.
1
taskQueue.realtimeStats.fetch(
2
function(error, statistics) {
3
if(error) {
4
console.log(error.code);
5
console.log(error.message);
6
return;
7
}
8
console.log("fetched taskQueue statistics: "+JSON.stringify(statistics));
9
console.log("total available workers: "+statistics.totalAvailableWorkers;
10
console.log("total eligible workers: "+statistics.totalEligibleWorkers;
11
}
12
);

on(event, callback)

taskqueue-on page anchor

Attaches a listener to the specified event. See Events for the complete list of supported events.

NameTypeDescription
eventStringAn event name. See Events for the complete list of supported events.
callbackFunctionA function that will be called when the specified Event is raised.
1
taskQueue.on("ready", function(taskQueue) {
2
console.log(taskQueue.friendlyName) // My TaskQueue
3
});

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.

NameTypeDescription
taskQueueTaskQueueThe created TaskQueue.
1
taskQueue.on("ready", function(taskQueue) {
2
console.log(taskQueue.friendlyName) // My TaskQueue
3
});

The TaskQueue has established a connection to TaskRouter.

1
taskQueue.on("connected", function() {
2
console.log("Websocket has connected");
3
});

The TaskQueue has disconnected a connection from TaskRouter.

1
taskQueue.on("disconnected", function() {
2
console.log("Websocket has disconnected");
3
});

Raised when the TaskRouter capability token used to create this TaskQueue expires.

1
taskQueue.on("token.expired", function() {
2
console.log("updating token");
3
var token = refreshJWT(); // your method to retrieve a new capability token
4
taskQueue.updateToken(token);
5
});

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.