Skip to content

JavaScript SDK

The Jetsocket JavaScript client library supports web browsers, web workers, and Node.js environments.

<script src="https://js.jetsocket.io/latest/jetsocket.min.js"></script>
Terminal window
npm install jetsocket-js
import Jetsocket from 'jetsocket-js';

For encrypted channels, use the encryption-enabled build:

<script src="https://js.jetsocket.io/latest/jetsocket-with-encryption.min.js"></script>
import Jetsocket from 'jetsocket-js/with-encryption';
Terminal window
npm install jetsocket-js
const Jetsocket = require('jetsocket-js');
importScripts('https://js.jetsocket.io/latest/jetsocket.worker.min.js');

Or with a bundler:

import Jetsocket from 'jetsocket-js/worker';
const jetsocket = new Jetsocket(APP_KEY, {
cluster: APP_CLUSTER,
});
const jetsocket = new Jetsocket(APP_KEY, {
cluster: APP_CLUSTER,
forceTLS: true,
channelAuthorization: {
endpoint: '/jetsocket/auth',
transport: 'ajax'
},
userAuthentication: {
endpoint: '/jetsocket/user-auth',
transport: 'ajax'
},
wsHost: 'ws.jetsocket.io',
wsPort: 443,
wssPort: 443,
httpHost: 'sockjs.jetsocket.io',
httpPort: 80,
httpsPort: 443,
httpPath: '/jetsocket',
statsHost: 'stats.jetsocket.io',
activityTimeout: 30000,
pongTimeout: 15000,
maxReconnectionAttempts: 6,
maxReconnectGap: 10000,
enableLogging: false,
ignoreNullOrigin: false,
enableStats: true,
auth: {
headers: {
'X-Custom-Header': 'value'
}
}
});
ParameterTypeDefaultDescription
clusterString-Your Jetsocket cluster
forceTLSBooleantrueForce TLS connections
channelAuthorization.endpointString/jetsocket/authAuthorization endpoint
channelAuthorization.transportStringajaxTransport method (ajax or jsonp)
userAuthentication.endpointString/jetsocket/user-authUser authentication endpoint
wsHostStringws.jetsocket.ioWebSocket host
wsPortNumber443WebSocket port
wssPortNumber443WebSocket secure port
activityTimeoutNumber30000Connection timeout
pongTimeoutNumber15000Pong timeout
maxReconnectionAttemptsNumber6Max reconnection attempts
enableLoggingBooleanfalseEnable debug logging
jetsocket.connection.bind('connected', () => {
console.log('Connected to Jetsocket');
});
jetsocket.connection.bind('disconnected', () => {
console.log('Disconnected from Jetsocket');
});
jetsocket.connection.bind('error', (error) => {
console.error('Connection error:', error);
});
jetsocket.connection.bind('state_change', (states) => {
console.log('Connection state changed from', states.previous, 'to', states.current);
});
console.log(jetsocket.connection.state); // 'connected', 'connecting', 'disconnected', 'failed'
console.log(jetsocket.connection.connected); // true/false
jetsocket.connection.bind('connected', () => {
console.log('Socket ID:', jetsocket.connection.socket_id);
});
// Public channel
const publicChannel = jetsocket.subscribe('my-channel');
// Private channel
const privateChannel = jetsocket.subscribe('private-my-channel');
// Presence channel
const presenceChannel = jetsocket.subscribe('presence-my-channel');
// Encrypted channel
const encryptedChannel = jetsocket.subscribe('private-encrypted-my-channel');
const channel = jetsocket.subscribe('my-channel');
channel.bind('jetsocket:subscription_succeeded', () => {
console.log('Successfully subscribed to channel');
});
channel.bind('jetsocket:subscription_error', (error) => {
console.error('Subscription error:', error);
});
jetsocket.unsubscribe('my-channel');
// Get a specific channel
const channel = jetsocket.channel('my-channel');
// Get all subscribed channels
const allChannels = jetsocket.allChannels();
allChannels.forEach(channel => {
console.log('Subscribed to:', channel.name);
});
const channel = jetsocket.subscribe('my-channel');
// Bind to specific event
channel.bind('new-message', (data) => {
console.log('New message:', data);
});
// Bind with context
channel.bind('my-event', function() {
console.log('Hello', this.name);
}, { name: 'Jetsocket' });
// Bind to all events
channel.bind_global((eventName, data) => {
console.log(`Event ${eventName}:`, data);
});
const handler = (data) => console.log(data);
// Bind event
channel.bind('my-event', handler);
// Unbind specific handler
channel.unbind('my-event', handler);
// Unbind all handlers for an event
channel.unbind('my-event');
// Unbind all events
channel.unbind();
// Unbind all global handlers
channel.unbind_global();
// Unbind everything
channel.unbind_all();

Client events can only be triggered on private and presence channels:

const channel = jetsocket.subscribe('private-my-channel');
// Trigger client event
channel.trigger('client-my-event', { message: 'Hello from client!' });
// Listen for client events
channel.bind('client-my-event', (data, metadata) => {
console.log('Client event from', metadata.user_id, ':', data);
});
const presenceChannel = jetsocket.subscribe('presence-my-channel');
presenceChannel.bind('jetsocket:subscription_succeeded', (members) => {
console.log('Current members:', members);
});
presenceChannel.bind('jetsocket:member_added', (member) => {
console.log('Member joined:', member);
});
presenceChannel.bind('jetsocket:member_removed', (member) => {
console.log('Member left:', member);
});
presenceChannel.bind('jetsocket:subscription_succeeded', (members) => {
// Get member count
console.log('Member count:', presenceChannel.members.count);
// Get all members
const allMembers = presenceChannel.members.members;
// Check if specific user is present
const isPresent = presenceChannel.members.get('user-123');
// Get member info
if (isPresent) {
console.log('User info:', isPresent.info);
}
});
jetsocket.connection.bind('error', (error) => {
console.error('Connection error:', error);
// Handle specific error types
if (error.type === 'WebSocketError') {
console.log('WebSocket connection failed');
} else if (error.type === 'HTTPError') {
console.log('HTTP connection failed');
}
});
const channel = jetsocket.subscribe('private-my-channel');
channel.bind('jetsocket:subscription_error', (error) => {
console.error('Subscription error:', error);
if (error.status === 403) {
console.log('Access denied to channel');
} else if (error.status === 404) {
console.log('Channel not found');
}
});
jetsocket.bind_global((eventName, data) => {
if (eventName === 'jetsocket:error') {
console.error('Global error:', data);
}
});
// Check if connected
if (jetsocket.connection.connected) {
console.log('Connected');
}
// Get connection state
console.log(jetsocket.connection.state);
// Get socket ID
console.log(jetsocket.connection.socket_id);
// Check if subscribed to channel
const channel = jetsocket.channel('my-channel');
console.log(channel.subscribed);
// Get channel name
console.log(channel.name);
// Get all channels
const channels = jetsocket.allChannels();

The Jetsocket JavaScript library supports:

  • Chrome: 16+
  • Firefox: 11+
  • Safari: 7+
  • Edge: 12+
  • Internet Explorer: 10+ (with polyfills)
import Jetsocket from 'jetsocket-js';
import * as JetsocketTypes from 'jetsocket-js';
const jetsocket: JetsocketTypes.Jetsocket = new Jetsocket("APP_KEY", {
cluster: "APP_CLUSTER",
});
const channel: JetsocketTypes.Channel = jetsocket.subscribe('my-channel');
const presenceChannel: JetsocketTypes.PresenceChannel = jetsocket.subscribe('presence-my-channel');
<!DOCTYPE html>
<html>
<head>
<script src="https://js.jetsocket.io/latest/jetsocket.min.js"></script>
</head>
<body>
<div id="messages"></div>
<input type="text" id="messageInput" placeholder="Type a message...">
<button onclick="sendMessage()">Send</button>
<script>
const jetsocket = new Jetsocket("APP_KEY", {
cluster: "APP_CLUSTER",
});
const channel = jetsocket.subscribe("chat-room");
const messagesDiv = document.getElementById("messages");
// Connection events
jetsocket.connection.bind('connected', () => {
console.log('Connected to Jetsocket');
});
jetsocket.connection.bind('error', (error) => {
console.error('Connection error:', error);
});
// Channel events
channel.bind('jetsocket:subscription_succeeded', () => {
console.log('Subscribed to chat room');
});
channel.bind('new-message', (data) => {
const messageElement = document.createElement("div");
messageElement.textContent = `${data.username}: ${data.message}`;
messagesDiv.appendChild(messageElement);
});
function sendMessage() {
const input = document.getElementById("messageInput");
const message = input.value;
if (message.trim()) {
// Send to server
fetch("/send-message", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message })
});
input.value = "";
}
}
</script>
</body>
</html>