Registry / communication / twilsock

twilsock

JSON →
library1.0.1jsnpmunverified

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.

npm install twilsock
INSTALL
IMPORT
SIG · TWILSOCK
T
twilsock
communicationjavascriptv1.0.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Twilsock
import { Twilsock } from 'twilsock';
const Twilsock = require('twilsock');
The primary class for instantiating the Twilsock client. While CommonJS `require` might work in some environments, ESM named imports are the recommended modern approach for Node.js projects with TypeScript.
Twilsock.ConnectionState
import { Twilsock, TwilsockConnectionState } from 'twilsock'; // or import type { TwilsockConnectionState } from 'twilsock';
Twilsock typically exposes types and enums for connection states (e.g., `CONNECTED`, `DISCONNECTED`). Use named imports for these.

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);
Debug
Known issues
breakingWhen 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.
fix
If providing a custom `Twilsock` instance, ensure you manually call `connect()` on that instance. Otherwise, allow the SDK to manage its internal `Twilsock` client.
affects: >=1.0.0
gotchaTwilio 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.
fix
Implement a secure server-side endpoint to generate Twilio Access Tokens. This endpoint should use your Twilio Account SID and Auth Token (kept secret on the server) to create a token with the appropriate grants and user identity, then return it to your client-side application.
affects: >=1.0.0
gotchaThe 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.
fix
Monitor your application's message rates. If high message volumes are expected, ensure your application logic handles message queuing, rate limiting, or consult Twilio support to discuss increasing account limits if legitimate high throughput is required.
affects: >=1.0.0
gotchaThe `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.
fix
Ensure your Node.js environment is version 20 or newer. Use `nvm` or similar tools to manage Node.js versions if necessary.
affects: >=1.0.0
Errors
Common errors & fixes
Error: Can't connect to twilsock
This error typically indicates an issue with the Twilio Access Token (invalid, expired, incorrect identity) or a network connectivity problem to the Twilsock endpoint.
fix
Verify 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
This usually means the `Twilsock` class was not imported correctly, or the module being imported does not export a constructor named `Twilsock`.
fix
Ensure 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.
Upgrade
Version history
1.0.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
21 hits · last 30 days
node
18
Amazon
1
OpenAI (training)
1
Resources