Twilio Sync Client Library

4.0.0 · active · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

Demonstrates initializing the SyncClient with an access token, opening a Sync Document, listening for updates, and performing a data update operation. Includes basic error handling and shutdown.

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);

view raw JSON →