Twilio Sync Client Library
The Twilio Sync JavaScript client library, currently at version 4.0.0, provides a robust solution for real-time state synchronization across browsers, mobile devices, and backend services. It enables two-way, low-latency communication, allowing applications to store and retrieve small amounts of data, such as device states or user settings, and have them instantly reflected everywhere. The library facilitates working with Sync objects like Documents, Lists, and Maps. While a strict release cadence isn't published, major versions introduce significant changes. A key differentiator is its tight integration with the broader Twilio ecosystem for identity management and access control, leveraging Twilio Access Tokens for secure client-side operations, making it suitable for building collaborative real-time features without complex backend infrastructure for state management.
Common errors
-
Error: Token is required for SyncClient.
cause The SyncClient constructor was called without a valid access token or with a null/undefined value.fixEnsure your application fetches a valid Twilio Sync Access Token from a server and passes it to the `SyncClient` constructor. -
Access Denied. Error code 20101. No active Grant for Sync service for the given identity.
cause The provided Access Token does not contain a Sync Grant, or the identity is incorrect, or the token is expired.fixVerify that your server-side token generation logic includes a Sync Grant (e.g., `new SyncGrant({ serviceSid: 'ISxxx' })`) and that the token is not expired. Also, confirm the identity used to generate the token matches expectations. -
Sync Error: Document 'MyDocument' not found.
cause Attempted to access a Sync Document by a unique name or SID that does not exist or for which the client lacks permissions.fixCheck the document name/SID for typos. Ensure the client's Access Token has the necessary permissions (e.g., `read`, `write`, `manage`) for the Sync Document. Create the document if it's expected to be new (`syncClient.document.create(...)`).
Warnings
- breaking Version 4.0.0 likely introduces breaking changes from previous major versions (e.g., v3.x). Always consult the official changelog for detailed migration steps and API adjustments.
- gotcha A valid Twilio Sync Access Token is critical for client authentication. Tokens must be generated securely on a server-side application or Twilio Function, not directly in the client.
- gotcha The `Twilio.Sync.Client` global object is only available when including the library via CDN `<script>` tag. When using `npm` with Node.js or bundlers, you must import `SyncClient` as a module.
Install
-
npm install twilio-sync -
yarn add twilio-sync -
pnpm add twilio-sync
Imports
- SyncClient
const SyncClient = require('twilio-sync');import { SyncClient } from 'twilio-sync'; - SyncClient (CJS)
import { SyncClient } from 'twilio-sync';const { SyncClient } = require('twilio-sync'); - SyncClient (Type)
import { SyncClient } from 'twilio-sync';import type { SyncClient } from 'twilio-sync';
Quickstart
import { SyncClient } from 'twilio-sync';
// Obtain a JWT access token from your server-side application or a Twilio Function.
// This token authenticates your client with the Twilio Sync service.
// For development, use process.env.TWILIO_SYNC_TOKEN ?? '' or similar.
const token = process.env.TWILIO_SYNC_TOKEN || '<your-access-token-here>';
if (!token) {
console.error('Twilio Sync Access Token is required. Please provide it.');
process.exit(1);
}
const syncClient = new SyncClient(token);
syncClient.document('MyDocument')
.then(function(document) {
console.log('Successfully opened Sync Document:', document.sid);
document.on('updated', function(event) {
console.log('Received Document update event. New data:', event.data);
});
const newData = { temperature: Math.floor(Math.random() * 10) + 20 };
return document.set(newData);
})
.then(function(updateResult) {
console.log('The Document was successfully updated', updateResult);
})
.catch(function(error) {
console.error('Unexpected error during Sync Document operation:', error);
});
// Handle client disconnection or token expiration
syncClient.on('connectionStateChanged', (state) => {
console.log('Sync connection state changed:', state);
});
// Keep the process alive for a bit to receive updates
setTimeout(() => {
console.log('Shutting down Sync client after a few updates.');
syncClient.shutdown();
}, 15000);