SockJS Client
SockJS-client is a browser JavaScript library (current stable version 1.6.1) that provides a WebSocket-like object, abstracting away underlying transport mechanisms. It aims to offer a coherent, cross-browser, full-duplex communication channel between the browser and a web server, even in environments without native WebSocket support or behind restrictive corporate proxies. The library first attempts to use native WebSockets, falling back to various browser-specific transports (like streaming or polling) if necessary. Releases are somewhat irregular but active, with recent updates focusing on security fixes and dependency updates. A key differentiator is its robust fallback mechanism, adhering closely to the HTML5 WebSocket API, and supporting cross-domain connections without requiring Flash. It explicitly requires a server counterpart, such as `sockjs-node`, for functionality.
Common errors
-
ReferenceError: SockJS is not defined
cause The SockJS client library was not correctly loaded or imported into the JavaScript environment. This often happens when mixing global script tag usage with module imports, or when the module bundler fails to resolve the import.fixIf using a module system (ESM/CommonJS), ensure you have `import SockJS from 'sockjs-client';` (or `const SockJS = require('sockjs-client');`). If loading via a script tag, ensure the `<script>` tag is correctly placed and the path to `sockjs.min.js` is correct. -
WebSocket connection to 'ws://localhost:8080/sockjs/info?t=...' failed: Error during WebSocket handshake: Unexpected response code: 500
cause The SockJS server endpoint is not correctly configured, not running, or is returning an error during the initial handshake. This often indicates a problem on the server side rather than the client.fixVerify that your SockJS server (e.g., `sockjs-node`) is running, accessible at the specified URL, and properly configured to handle SockJS connections. Check the server logs for specific error messages. -
Uncaught SyntaxError: The requested module './../node_modules/sockjs-client/lib/entry.js' does not provide an export named 'default'
cause This error typically occurs in ESM environments when `sockjs-client` is treated as an ES module but it primarily provides a CommonJS export, or when a bundler struggles to correctly transpile or interpret its module format.fixFor TypeScript, try `import * as SockJS from 'sockjs-client';`. For bundlers like Webpack or Rollup, ensure CommonJS plugins are correctly configured to handle `sockjs-client` (e.g., `@rollup/plugin-commonjs` for Rollup). You might also need to add `"type": "module"` to your `package.json` if using native ESM in Node.js, though `sockjs-client` might still require a CommonJS wrapper. -
SecurityError: Blocked a frame with origin "http://localhost:3000" from accessing a cross-origin frame.
cause This usually indicates a browser security restriction related to cross-origin communication, often when SockJS falls back to iframe-based transports, or if there are misconfigured CORS headers on the server.fixEnsure your SockJS server explicitly sets appropriate CORS headers (`Access-Control-Allow-Origin`, etc.) for your client's origin. For iframe transports, connecting from the same parent domain as the main site can help.
Warnings
- breaking SockJS-client v1.6.0 removed `agent: false` to allow usage of `globalAgent` in Node.js environments. This change could subtly alter HTTP agent behavior, potentially affecting proxy or connection pooling configurations for Node.js clients.
- breaking Version 1.3.0 reverted the `debug` dependency from v4 (which used ES6) back to `^3`. Projects explicitly relying on `debug` v4 features or ES6 syntax from the `debug` library might experience issues if `sockjs-client` is a transitive dependency that forces an older `debug` version.
- gotcha SockJS requires a dedicated server-side implementation (e.g., `sockjs-node` for Node.js, or similar for other languages). It is not a standalone WebSocket server but a client library for a specific protocol.
- gotcha When connecting from the browser via script tag, the `SockJS` object is globally available. However, in modern module-based environments (ESM/CommonJS), it must be explicitly imported, typically as a default export. Incorrect import statements are a common source of 'SockJS is not defined' errors.
- gotcha SockJS uses iframe-based transports for cross-origin communication in some older browsers. This can lead to issues with `webpack-dev-server` if there's a version mismatch of `sockjs-client` between the bundled client and the main application, resulting in 'Incompatible SockJS!' errors.
- gotcha SockJS has an in-browser limitation preventing more than one active SockJS connection to a single domain simultaneously, as each session uses two outgoing connections (one for sending, one for receiving). Attempting to open multiple connections can lead to unexpected behavior or connection failures.
Install
-
npm install sockjs-client -
yarn add sockjs-client -
pnpm add sockjs-client
Imports
- SockJS
const SockJS = require('sockjs-client');import SockJS from 'sockjs-client';
- SockJS (browser global)
<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script> // SockJS is then available as a global variable
- SockJS (TypeScript)
import { SockJS } from 'sockjs-client';import SockJS from 'sockjs-client'; // Or if type errors occur: import * as SockJS from 'sockjs-client';
Quickstart
import SockJS from 'sockjs-client';
// Ensure a SockJS server is running, e.g., on http://localhost:8080/my_websocket
// For example, using sockjs-node:
// const sockjs = require('sockjs');
// const http = require('http');
// const server = http.createServer();
// const echo = sockjs.createServer();
// echo.on('connection', (conn) => {
// conn.on('data', (message) => { conn.write(message); });
// conn.on('close', () => { console.log('Client disconnected from server'); });
// });
// echo.installHandlers(server, { prefix: '/my_websocket' });
// server.listen(8080, '0.0.0.0', () => { console.log('SockJS server listening on 8080'); });
const socket = new SockJS('http://localhost:8080/my_websocket');
socket.onopen = () => {
console.log('SockJS connection opened');
socket.send('Hello from client!');
};
socket.onmessage = (event) => {
console.log('Received message:', event.data);
// Optionally close the connection after receiving a message
// socket.close();
};
socket.onclose = (event) => {
console.log('SockJS connection closed:', event.code, event.reason);
if (!event.wasClean) {
console.error('Connection abruptly disconnected.');
// Implement re-connection logic here
}
};
socket.onerror = (error) => {
console.error('SockJS error:', error);
};
// Example: Send a message every 3 seconds
// setInterval(() => {
// if (socket.readyState === SockJS.OPEN) {
// socket.send('Ping!');
// }
// }, 3000);