realtimex-js
v1.3.0
Published
JavaScript client library for RealtimeX
Maintainers
Readme
RealtimeX JavaScript SDK
JavaScript client library for RealtimeX real-time messaging service.
Installation
NPM
npm install realtimex-jsCDN
<script src="https://cdn.realtimex.net/realtimex.min.js"></script>Quick Start
// Initialize
const realtimex = new RealtimeX('YOUR_API_KEY', {
cluster: 'eu', // optional, default 'eu'
wsHost: 'ws.realtimex.net', // optional
wsPort: 443, // optional
encrypted: true, // optional, default true
});
// Subscribe to a channel
const channel = realtimex.subscribe('my-channel');
// Listen for events
channel.bind('my-event', (data) => {
console.log('Received:', data);
});
// Send client events
channel.trigger('client-my-event', {
message: 'Hello'
});API Reference
RealtimeX
Constructor
const realtimex = new RealtimeX(apiKey, options)Parameters:
apiKey(string): Your RealtimeX API keyoptions(object, optional): Configuration optionscluster(string): Server cluster, default 'eu'wsHost(string): WebSocket hostwsPort(number): WebSocket portencrypted(boolean): Use WSS, default trueauthEndpoint(string): Required for private and presence channels. Must return auth signature
Methods
subscribe(channelName)
const channel = realtimex.subscribe('my-channel');
const privateChannel = realtimex.subscribe('private-my-channel');
const presenceChannel = realtimex.subscribe('presence-my-channel');unsubscribe(channelName)
realtimex.unsubscribe('my-channel');disconnect()
realtimex.disconnect();Channel
Methods
bind(event, callback)
channel.bind('my-event', (data) => {
console.log('Event data:', data);
});bind_global(callback)
channel.bind_global((event, data) => {
console.log(`Event ${event}:`, data);
});trigger(event, data)
// Client events must start with 'client-'
channel.trigger('client-my-event', {
message: 'Hello World'
});unbind(event, callback?)
// Remove specific callback
channel.unbind('my-event', myCallback);
// Remove all callbacks for event
channel.unbind('my-event');unsubscribe()
channel.unsubscribe();Connection Events
realtimex.connection.bind('connected', () => {
console.log('Connected to RealtimeX');
});
realtimex.connection.bind('disconnected', () => {
console.log('Disconnected from RealtimeX');
});
realtimex.connection.bind('error', (err) => {
console.error('Connection error:', err);
});Channel Types
Public Channels
const channel = realtimex.subscribe('my-channel');Private Channels
const privateChannel = realtimex.subscribe('private-my-channel');Presence Channels
const presenceChannel = realtimex.subscribe('presence-my-channel');Authentication
Private and presence channels require authentication. You must provide an authEndpoint that returns authorization data.
Note: There is no default authEndpoint. If you attempt to subscribe to a private or presence channel without providing authEndpoint, an error will be thrown.
Setup Auth Endpoint
const realtimex = new RealtimeX('YOUR_API_KEY', {
authEndpoint: 'https://your-backend.com/auth' // Required for private/presence channels
});Auth Endpoint Implementation
Your backend must implement a POST endpoint that:
- Receives
{socket_id, channel_name}in request body - Returns
{auth: "key:signature"}response
Request Format:
{
"socket_id": "SZ7iV2C0J9Fd9vjgAABB",
"channel_name": "private-test-channel"
}Response Format:
{
"auth": "your_app_key:generated_signature"
}Presence Channels
Presence channels require both auth and channel_data (stringified JSON with user information).
Example:
const presence = realtimex.subscribe('presence-chat');Expected server auth response for presence channels:
{
"auth": "your_app_key:generated_signature",
"channel_data": "{\"user_id\":\"123\", \"user_info\": {\"name\":\"Alice\"}}"
}Example (Node.js):
app.post('/auth', (req, res) => {
const {socket_id, channel_name} = req.body;
const auth = crypto
.createHmac('sha256', YOUR_APP_SECRET)
.update(`${socket_id}:${channel_name}`)
.digest('hex');
const response = {
auth: `${YOUR_APP_KEY}:${auth}`
};
// For presence channels, add channel_data
if (channel_name.startsWith('presence-')) {
response.channel_data = JSON.stringify({
user_id: "123",
user_info: { name: "Alice" }
});
}
res.json(response);
});SDK Request: SDK sends a POST request to authEndpoint with JSON body. You may customize authentication on your backend.
WebSocket Protocol
Connection
ws://your-host:port?api_key=YOUR_API_KEYMessage Format
Subscribe:
{
"event": "realtimex:subscribe",
"data": {
"channel": "my-channel",
"auth": "<optional-auth>",
"channel_data": "<optional-json>"
}
}Unsubscribe:
{
"event": "realtimex:unsubscribe",
"data": {
"channel": "my-channel"
}
}Successful Subscription:
{
"event": "realtimex_internal:subscription_succeeded",
"data": {
"channel": "my-channel",
"initial_state": {}
}
}Client Event:
{
"event": "client-my-event",
"channel": "my-channel",
"data": { "message": "Hello" }
}Server Event:
{
"event": "server-event",
"data": {
"event": "my-event",
"channel": "my-channel",
"data": { "message": "Hello" }
}
}Compatibility
Browser Support
- Chrome 16+
- Firefox 11+
- Safari 7+
- Edge 12+
- Internet Explorer 10+
Node.js Support
- Node.js 14+
- Requires
socket.io-clientdependency
Module Formats
- ES Modules (ESM):
import { RealtimeX } from 'realtimex-js' - CommonJS:
const { RealtimeX } = require('realtimex-js') - UMD: Available via CDN for browser
<script>tags
Reconnection
RealtimeX SDK automatically handles connection failures and reconnects:
- Fixed delay: 3 seconds between reconnection attempts (no exponential backoff)
- Automatic resubscription: All existing channels are automatically resubscribed after reconnect
- Event firing:
connectedevent fires after each successful reconnection - Channel preservation: Channel instances remain valid across reconnections
- Pending subscriptions: Subscriptions made while disconnected are queued and sent on reconnect
Example:
realtimex.connection.bind('connected', () => {
console.log('Connected (or reconnected)');
});
realtimex.connection.bind('disconnected', () => {
console.log('Disconnected - will auto-reconnect in 3s');
});Features
✅ WebSocket connection management
✅ Channel subscription/unsubscription
✅ Event listening and triggering
✅ Client events
✅ Automatic reconnection
✅ TypeScript support
✅ JSDoc documentation
✅ Unit tests with Jest
✅ UMD and ESM builds
Development
# Install dependencies
npm install
# Build
npm run build
# Development mode
npm run dev
# Run tests
npm testLicense
MIT
