SockJS-client is a browser JavaScript library that provides a WebSocket-like object for establishing cross-browser, full-duplex communication channels between browsers and web servers.
npx @tessl/cli install tessl/npm-sockjs-client@1.6.0SockJS-client is a browser JavaScript library that provides a WebSocket-like object for establishing cross-browser, full-duplex communication channels between browsers and web servers. It creates low-latency, cross-domain communication by first attempting to use native WebSockets and falling back to various browser-specific transport protocols when WebSockets are unavailable.
The library maintains compatibility with the HTML5 WebSocket API while providing robust fallback mechanisms for older browsers and constrained network environments, including support for restrictive corporate proxies and cross-domain connections.
npm install sockjs-clienthttps://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.jsFor browser environments using CDN:
<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>For Node.js or bundlers:
const SockJS = require('sockjs-client');ES modules:
import SockJS from 'sockjs-client';// Create connection
const sock = new SockJS('https://mydomain.com/my_prefix');
// Set up event handlers
sock.onopen = function() {
console.log('Connected');
sock.send('Hello Server!');
};
sock.onmessage = function(e) {
console.log('Received:', e.data);
};
sock.onclose = function() {
console.log('Disconnected');
};
sock.onerror = function() {
console.log('Connection error');
};
// Later: close connection
sock.close();SockJS-client is built around several key components:
Primary SockJS class providing WebSocket-compatible interface for establishing and managing connections with automatic transport fallback.
/**
* SockJS constructor - creates a new SockJS connection
* @param {string} url - Connection URL (http/https), may contain query string
* @param {string|string[]} [protocols] - Protocols (reserved parameter, typically not used)
* @param {object} [options] - Configuration options
*/
function SockJS(url, protocols, options);
// Instance properties
SockJS.prototype.url; // string - Connection URL
SockJS.prototype.readyState; // number - Current connection state (0-3)
SockJS.prototype.extensions; // string - Always empty string
SockJS.prototype.protocol; // string - Always empty string
SockJS.prototype.transport; // string - Active transport name when connected
// Instance methods
SockJS.prototype.send(data); // Send data (converts non-strings to strings)
SockJS.prototype.close(code, reason); // Close connection with optional code and reason
// Static constants
SockJS.CONNECTING; // 0 - Connection being established
SockJS.OPEN; // 1 - Connection is open
SockJS.CLOSING; // 2 - Connection is closing
SockJS.CLOSED; // 3 - Connection is closed
// Static property
SockJS.version; // string - Library versionDOM-compatible event handling system supporting both event handler properties and addEventListener/removeEventListener methods.
// Event handler properties
sock.onopen = function() { /* connection opened */ };
sock.onmessage = function(e) { /* message received: e.data */ };
sock.onclose = function(e) { /* connection closed: e.code, e.reason, e.wasClean */ };
sock.onerror = function() { /* connection error */ };
// EventTarget methods
sock.addEventListener(type, listener); // Add event listener
sock.removeEventListener(type, listener); // Remove event listener
sock.dispatchEvent(event); // Dispatch eventFlexible transport system with automatic fallback and manual configuration options for different network environments and browser capabilities.
// Constructor options for transport configuration
const options = {
server: string, // Server identifier (default: random 4-digit number)
transports: string|Array, // Whitelist of allowed transports
sessionId: number|function, // Session ID generation (default: 8 chars)
timeout: number, // Minimum timeout for transport connections
transportOptions: object // Transport-specific configuration
};
// Available transport names for whitelisting
const availableTransports = [
'websocket',
'xhr-streaming',
'xdr-streaming',
'eventsource',
'iframe-eventsource',
'htmlfile',
'iframe-htmlfile',
'xhr-polling',
'xdr-polling',
'iframe-xhr-polling',
'jsonp-polling'
];// Options interface for SockJS constructor
interface SockJSOptions {
server?: string; // Server identifier
transports?: string | string[]; // Transport whitelist
sessionId?: number | (() => string); // Session ID configuration
timeout?: number; // Connection timeout
transportOptions?: object; // Transport-specific options
}
// Event objects
interface SockJSMessageEvent {
type: 'message';
data: any; // Message payload
}
interface SockJSCloseEvent {
type: 'close';
code: number; // Close code
reason: string; // Close reason
wasClean: boolean; // Clean close flag
}
interface SockJSEvent {
type: 'open' | 'error' | 'heartbeat';
}SockJS-client provides comprehensive browser support through its transport fallback system:
The library automatically selects the best available transport based on browser capabilities and network environment.