Skip to contentSkip to navigationSkip to topbar
On this page

Issuing Sync Tokens


In any Sync application, your work will span two components.

  • An SDK-driven client app (browser, iOS, Android), where users interact with Sync objects.
  • A backend server which vouches for your users' identities by providing Access Tokens.

Since any Twilio SDK-driven app requires an Access Token to run, most will have code like the below to retrieve a token.

1
function fetchAccessToken(handler) {
2
// We use jQuery to make an Ajax request to our server to retrieve our
3
// Access Token
4
$.getJSON('/token', function(data) {
5
// The data sent back from the server should contain a long string, which
6
// is the token you'll need to initialize the SDK. This string is in a format
7
// called JWT (JSON Web Token) - more at http://jwt.io
8
console.log(data.token);
9
10
// Since the starter app doesn't implement authentication, the server sends
11
// back a randomly generated username for the current client, which is how
12
// they will be identified while sending messages. If your app has a login
13
// system, you should use the email address or username that uniquely identifies
14
// a user instead.
15
console.log(data.identity);
16
17
handler(data);
18
});
19
}

In this guide, we'll examine how to handle this request on the server and create a valid token for the client.


Minting an Access Token in your Backend

minting-an-access-token-in-your-backend page anchor

On the server we must decide, based on the token request that was sent to us, who the user is and what they should be allowed to do. To do this you might use your existing login system (using session cookies, an API token, or whatever mechanism you use to secure API requests or pages today). You might not care who a user is at all, and assign them a temporary identity. Who the user is and how you determine that will vary from app to app.

Assuming that the requesting user is authorized, your backend should respond with a signed token. Here's an example of generating those tokens in Node.js.

We recommend following the standard URI specification and avoid the following reserved characters ! * ' ( ) ; : @ & = + $ , / ? % # [ ] for values such as identity and friendly name.

1
require('dotenv').load();
2
var http = require('http');
3
var path = require('path');
4
5
var AccessToken = require('twilio').jwt.AccessToken;
6
var SyncGrant = AccessToken.SyncGrant;
7
var express = require('express');
8
9
// Create Express webapp
10
var app = express();
11
app.use(express.static(path.join(__dirname, 'public')));
12
13
/*
14
Generate an Access Token for a Sync application user - it generates a random
15
username for the client requesting a token, and takes a device ID as a query
16
parameter.
17
*/
18
app.get('/token', function(request, response) {
19
20
//
21
// This is the most critical part of your backend code, as you must identify the user and (possibly)
22
// challenge them with some authentication scheme. To determine the identity, you might use:
23
// * A session datum consistently identifying one anonymous visitor,
24
// * A session key identifying a logged-in user
25
// * OAuth credentials identifying a logged-in user
26
// * A random username for all comers.
27
//
28
var identity = authenticatedSenderOf(request);
29
30
// Create a "grant" identifying the Sync service instance for this app.
31
var syncGrant = new SyncGrant({
32
serviceSid: process.env.TWILIO_SYNC_SERVICE_SID,
33
});
34
35
// Create an access token which we will sign and return to the client,
36
// containing the grant we just created and specifying his identity.
37
var token = new AccessToken(
38
process.env.TWILIO_ACCOUNT_SID,
39
process.env.TWILIO_API_KEY,
40
process.env.TWILIO_API_SECRET
41
);
42
token.addGrant(syncGrant);
43
token.identity = identity;
44
45
// Serialize the token to a JWT string and include it in a JSON response
46
response.send({
47
identity: identity,
48
token: token.toJwt()
49
});
50
});
51
52
// Create http server and run it
53
var server = http.createServer(app);
54
var port = process.env.PORT || 3000;
55
server.listen(port, function() {
56
console.log('Express server running on *:' + port);
57
});
58

Applying the minted token to your SDK

applying-the-minted-token-to-your-sdk page anchor

Access Token in hand, we can now initialize the Sync SDK on the client to start doing fun stuff like subscribing to Sync objects. Here's how you would use the token string to initialize the client in JavaScript.

1
fetchAccessToken(initializeSync);
2
3
function initializeSync(tokenResponse) {
4
var syncClient = new Twilio.Sync.Client(tokenResponse.token);
5
6
// Use syncClient here
7
}

After you've initialized the client, you can access all of the SDK's features.


After supplying the access token to Sync SDK initially, renewing the token prior to its expiry is important for ensuring that your Sync application is a great user experience. For long living applications, you should refresh the token when either tokenAboutToExpire or tokenExpired events occur. Handling just one of them is sufficient. The tokenAboutToExpire trigger takes place three minutes before the JWT access token expiry.

1
syncClient.on('tokenAboutToExpire', function() {
2
// Obtain a JWT access token: https://www.twilio.com/docs/sync/identity-and-access-tokens
3
var token = '<your-access-token-here>';
4
syncClient.updateToken(token);
5
});

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.