Connection Guide
Connect to the ExportComments WebSocket API using the Centrifuge client SDK. The SDK handles connection management, automatic reconnection, and token refresh.
WebSocket Endpoint
bash
wss://exportcomments.com/connection/websocket
JavaScript / Node.js
Install the official Centrifuge client:
bash
npm install centrifuge
Full Example
javascript
import { Centrifuge } from 'centrifuge';const API_KEY = 'your-api-key';// Create client with automatic token managementconst client = new Centrifuge('wss://exportcomments.com/connection/websocket', {getToken: async () => {const res = await fetch('https://exportcomments.com/api/public/auth/socket', {method: 'POST',headers: { 'X-AUTH-TOKEN': API_KEY },});const data = await res.json();return data.token;},});// Connection state changesclient.on('state', (ctx) => {console.log(`State: ${ctx.oldState} → ${ctx.newState}`);});// Receive events from auto-subscribed channelsclient.on('publication', (ctx) => {const { event, guid, status } = ctx.data;switch (event) {case 'job.created':console.log(`Export ${guid} started`);break;case 'job.progress':console.log(`Export ${guid} progress: ${ctx.data.current}/${ctx.data.total}`);break;case 'job.finished':console.log(`Export ${guid} completed — download: ${ctx.data.url}`);break;case 'job.failed':console.log(`Export ${guid} failed`);break;}});// Handle errorsclient.on('error', (err) => {console.error('Connection error:', err);});// Connectclient.connect();// To disconnect later:// client.disconnect();
Subscribing to a Specific Job
If you only need updates for a single export, subscribe to its dedicated channel:
javascript
const jobGuid = 'b4219d47-3138-5efd-9762-2ef9f9495084';const sub = client.newSubscription(`export.${jobGuid}.job`);sub.on('publication', (ctx) => {console.log('Job event:', ctx.data.event, ctx.data);});sub.subscribe();
Python
Install the Centrifuge Python client:
bash
pip install centrifuge-python
Full Example
python
import asyncioimport aiohttpfrom centrifuge import Client, PublicationEventAPI_KEY = "your-api-key"WS_URL = "wss://exportcomments.com/connection/websocket"AUTH_URL = "https://exportcomments.com/api/public/auth/socket"async def get_token():async with aiohttp.ClientSession() as session:async with session.post(AUTH_URL, headers={"X-AUTH-TOKEN": API_KEY}) as resp:data = await resp.json()return data["token"]async def main():client = Client(WS_URL, token=await get_token())async def on_publication(event: PublicationEvent):data = event.dataevent_type = data.get("event")guid = data.get("guid")if event_type == "job.finished":print(f"Export {guid} completed!")elif event_type == "job.progress":print(f"Export {guid}: {data.get('current')}/{data.get('total')}")elif event_type == "job.failed":print(f"Export {guid} failed")client.on_publication = on_publicationawait client.connect()# Keep the connection alivetry:while True:await asyncio.sleep(1)except KeyboardInterrupt:await client.disconnect()asyncio.run(main())
Browser (HTML)
Include the SDK via CDN:
html
<script src="https://unpkg.com/centrifuge@5/dist/centrifuge.js"></script><script>const client = new Centrifuge('wss://exportcomments.com/connection/websocket', {getToken: async () => {const res = await fetch('https://exportcomments.com/api/public/auth/socket', {method: 'POST',headers: { 'X-AUTH-TOKEN': 'your-api-key' },});const data = await res.json();return data.token;},});client.on('publication', (ctx) => {console.log('Event received:', ctx.data);});client.connect();</script>
Connection Options
| Option | Default | Description |
|---|---|---|
getToken | — | Async function returning a JWT token string |
ping | true | Enable client-side ping to detect stale connections |
pingInterval | 25000 | Ping interval in milliseconds |
minReconnectDelay | 500 | Minimum delay before reconnect attempt (ms) |
maxReconnectDelay | 20000 | Maximum delay before reconnect attempt (ms) |
Connection Lifecycle
bash
disconnected → connecting → connected↑ ↓└── disconnected (auto-reconnect)
The SDK automatically reconnects with exponential backoff when the connection drops. Token refresh is handled by calling your getToken function again.
Keep your API key server-side
In browser applications, do not embed your API key directly in client-side code. Instead, create a backend endpoint that proxies the token request and returns only the JWT token to the browser.