Twilsock Client Library
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
-
Error: Can't connect to twilsock
cause This error typically indicates an issue with the Twilio Access Token (invalid, expired, incorrect identity) or a network connectivity problem to the Twilsock endpoint.fixVerify that the Access Token is freshly generated on your backend, contains the correct identity, and has not expired. Check network connectivity and firewall rules. Ensure the Twilsock URL is correct for your Twilio service. -
TypeError: Twilsock is not a constructor
cause This usually means the `Twilsock` class was not imported correctly, or the module being imported does not export a constructor named `Twilsock`.fixEnsure you are using `import { Twilsock } from 'twilsock';` for ESM environments with TypeScript. Double-check the package installation and file paths if you are attempting to import from a non-standard location.
Warnings
- breaking When integrating `twilsock` into other Twilio SDKs like Twilio Sync, explicitly passing your own `Twilsock` instance via options (e.g., `SyncClient` options) will prevent the SDK from automatically initiating the connection. Developers must manage the `Twilsock` connection lifecycle manually in such advanced scenarios.
- gotcha Twilio client-side SDKs, including those utilizing `twilsock`, require an Access Token that MUST be generated on your application's backend server. Using test credentials or attempting to generate tokens directly client-side is a common mistake and will lead to authentication failures.
- gotcha The TwilSock service has limits on the number of messages per connection. Exceeding these limits can result in an `ERROR: 51128: Twilsock: Too many messages per connection` and potential disconnection or degraded service.
- gotcha The `engines` field in `package.json` specifies `"node": ">=20"`. Running this package with older Node.js versions may lead to unexpected behavior or runtime errors, although it might install without warning.
Install
-
npm install twilsock -
yarn add twilsock -
pnpm add twilsock
Imports
- Twilsock
const Twilsock = require('twilsock');import { Twilsock } from 'twilsock'; - Twilsock.ConnectionState
import { Twilsock, TwilsockConnectionState } from 'twilsock'; // or import type { TwilsockConnectionState } from 'twilsock';
Quickstart
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);