{"id":12052,"library":"sockjs-client","title":"SockJS Client","description":"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.","status":"active","version":"1.6.1","language":"javascript","source_language":"en","source_url":"https://github.com/sockjs/sockjs-client","tags":["javascript","websockets","websocket"],"install":[{"cmd":"npm install sockjs-client","lang":"bash","label":"npm"},{"cmd":"yarn add sockjs-client","lang":"bash","label":"yarn"},{"cmd":"pnpm add sockjs-client","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"SockJS-client requires a compatible server-side implementation to establish connections and handle communication. `sockjs-node` is the official Node.js server counterpart.","package":"sockjs-node"}],"imports":[{"note":"ESM import is recommended for modern JavaScript environments and module bundlers.","wrong":"const SockJS = require('sockjs-client');","symbol":"SockJS","correct":"import SockJS from 'sockjs-client';"},{"note":"When included directly via a script tag in HTML, SockJS becomes a global object.","symbol":"SockJS (browser global)","correct":"<script src=\"https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js\"></script>\n// SockJS is then available as a global variable"},{"note":"TypeScript users might need `import * as SockJS from 'sockjs-client';` or `declare module 'sockjs-client';` if declaration files are missing or incompatible, especially with older configurations. Installing `@types/sockjs-client` is also a common step if available.","wrong":"import { SockJS } from 'sockjs-client';","symbol":"SockJS (TypeScript)","correct":"import SockJS from 'sockjs-client';\n// Or if type errors occur: import * as SockJS from 'sockjs-client';"}],"quickstart":{"code":"import SockJS from 'sockjs-client';\n\n// Ensure a SockJS server is running, e.g., on http://localhost:8080/my_websocket\n// For example, using sockjs-node:\n// const sockjs = require('sockjs');\n// const http = require('http');\n// const server = http.createServer();\n// const echo = sockjs.createServer();\n// echo.on('connection', (conn) => {\n//   conn.on('data', (message) => { conn.write(message); });\n//   conn.on('close', () => { console.log('Client disconnected from server'); });\n// });\n// echo.installHandlers(server, { prefix: '/my_websocket' });\n// server.listen(8080, '0.0.0.0', () => { console.log('SockJS server listening on 8080'); });\n\nconst socket = new SockJS('http://localhost:8080/my_websocket');\n\nsocket.onopen = () => {\n  console.log('SockJS connection opened');\n  socket.send('Hello from client!');\n};\n\nsocket.onmessage = (event) => {\n  console.log('Received message:', event.data);\n  // Optionally close the connection after receiving a message\n  // socket.close();\n};\n\nsocket.onclose = (event) => {\n  console.log('SockJS connection closed:', event.code, event.reason);\n  if (!event.wasClean) {\n    console.error('Connection abruptly disconnected.');\n    // Implement re-connection logic here\n  }\n};\n\nsocket.onerror = (error) => {\n  console.error('SockJS error:', error);\n};\n\n// Example: Send a message every 3 seconds\n// setInterval(() => {\n//   if (socket.readyState === SockJS.OPEN) {\n//     socket.send('Ping!');\n//   }\n// }, 3000);\n","lang":"typescript","description":"Demonstrates how to establish a connection with a SockJS server, send messages, and handle connection lifecycle events like opening, receiving messages, and closing. It also highlights the necessity of a server counterpart."},"warnings":[{"fix":"Review Node.js client configurations, especially those relying on `agent: false` behavior or custom HTTP agents, to ensure compatibility with `globalAgent` usage. Explicitly define HTTP agents if specific behavior is required.","message":"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.","severity":"breaking","affected_versions":">=1.6.0"},{"fix":"Ensure your project's `debug` dependency aligns with `sockjs-client`'s requirement or use dependency overrides if possible. Check for `debug` related errors during build or runtime.","message":"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.","severity":"breaking","affected_versions":">=1.3.0 <1.4.0"},{"fix":"Ensure a compatible SockJS server is correctly deployed and accessible at the specified URL. The client cannot connect to a standard WebSocket server without a SockJS server in between.","message":"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.","severity":"gotcha","affected_versions":">=0.0.1"},{"fix":"For ESM, use `import SockJS from 'sockjs-client';`. For CommonJS, use `const SockJS = require('sockjs-client');`. If using TypeScript, `import * as SockJS from 'sockjs-client';` or `declare module 'sockjs-client';` might be necessary.","message":"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.","severity":"gotcha","affected_versions":">=0.0.1"},{"fix":"Ensure that all `sockjs-client` versions in your project's dependency tree (including transitive dependencies from tools like `webpack-dev-server`) are consistent. Upgrading `webpack-dev-server` to its latest major version is often recommended to resolve such issues.","message":"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.","severity":"gotcha","affected_versions":">=1.5.0"},{"fix":"Design your application to utilize a single SockJS connection per domain, multiplexing messages over that single channel if necessary. Avoid creating multiple `new SockJS()` instances to the same server endpoint.","message":"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.","severity":"gotcha","affected_versions":">=0.0.1"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"If 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.","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.","error":"ReferenceError: SockJS is not defined"},{"fix":"Verify 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.","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.","error":"WebSocket connection to 'ws://localhost:8080/sockjs/info?t=...' failed: Error during WebSocket handshake: Unexpected response code: 500"},{"fix":"For 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.","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.","error":"Uncaught SyntaxError: The requested module './../node_modules/sockjs-client/lib/entry.js' does not provide an export named 'default'"},{"fix":"Ensure 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.","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.","error":"SecurityError: Blocked a frame with origin \"http://localhost:3000\" from accessing a cross-origin frame."}],"ecosystem":"npm"}