Twilsock Client Library

1.0.1 · active · verified Tue Apr 21

Twilsock is a foundational client library that provides a WebSocket transport service for various Twilio products and SDKs. Functioning as a persistent bi-directional communication channel, it enables real-time data exchange between client-side applications (like web browsers or mobile SDKs) and Twilio's backend services, notably used within Twilio Sync and Conversations SDKs for features such as state synchronization and publish-subscribe messaging. This library, currently at version 1.0.1 with a modern Node.js 20+ engine requirement, serves as a lower-level component, handling the complexities of WebSocket connection management and message routing for higher-level Twilio services. While often an internal dependency, it can be interacted with directly for custom real-time integrations. Its release cadence is closely tied to the broader Twilio ecosystem, where continuous updates and integration improvements are common across its client SDKs. Key differentiators include its tight integration with Twilio's robust backend infrastructure and its role in enabling critical real-time features for Twilio's communication platforms.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to initialize the Twilsock client, establish a connection using a (server-generated) access token, handle common connection events, and send/receive basic messages.

import { Twilsock } from 'twilsock';

// In a real application, the ACCESS_TOKEN would be securely fetched from your server.
// DO NOT hardcode Twilio Access Tokens or API keys in client-side code.
// For demonstration, we'll use a placeholder and emphasize server-side generation.
const getAccessTokenFromServer = async (): Promise<string> => {
  // Replace with actual server endpoint to generate Twilio Access Token
  // For example: fetch('/api/twilio-token', { method: 'POST' }).then(res => res.json()).then(data => data.token);
  console.warn('Fetching a placeholder access token. In production, this must come from your backend.');
  return process.env.TWILIO_ACCESS_TOKEN ?? 'YOUR_GENERATED_TWILIO_ACCESS_TOKEN';
};

const main = async () => {
  const accessToken = await getAccessTokenFromServer();
  if (!accessToken || accessToken === 'YOUR_GENERATED_TWILIO_ACCESS_TOKEN') {
    console.error('Failed to get a valid Twilio Access Token. Please provide one.');
    return;
  }

  // Example Twilsock URL. This would be specific to your Twilio service/region.
  const twilsockUrl = 'wss://your-twiliosock-endpoint.twilio.com/v1/ws';

  const client = new Twilsock(twilsockUrl, accessToken, {
    // Optional: Add logging or other configuration
    logLevel: 'debug',
  });

  client.on('connected', () => {
    console.log('Twilsock client connected successfully!');
    // You can now send messages or interact with Twilio services
    client.sendMessage('Hello Twilio!');
  });

  client.on('message', (message: string) => {
    console.log('Received message:', message);
  });

  client.on('disconnected', (reason: string) => {
    console.log('Twilsock client disconnected:', reason);
  });

  client.on('error', (error: Error) => {
    console.error('Twilsock client error:', error.message);
  });

  console.log('Connecting to Twilsock...');
  client.connect();

  // Disconnect after some time for demonstration
  setTimeout(() => {
    console.log('Disconnecting Twilsock after 10 seconds...');
    client.disconnect();
  }, 10000);
};

main().catch(console.error);

view raw JSON →