{"id":12050,"library":"socketcluster-client","title":"SocketCluster Client","description":"SocketCluster Client (socketcluster-client) is the JavaScript client library for connecting to SocketCluster servers, enabling high-performance, real-time, bi-directional communication over WebSockets. It provides abstractions for pub/sub (channels), remote procedure calls (RPC), and efficient data streaming. The library is currently at version 20.0.1, indicating an active development cycle with frequent major releases that often introduce breaking changes. Key differentiators include its focus on scalability, built-in support for backpressure handling, and a clear API for consuming events and data streams using async iterators, making it suitable for demanding real-time applications like chat, gaming, and financial dashboards. It is designed to work seamlessly with `socketcluster-server`.","status":"active","version":"20.0.1","language":"javascript","source_language":"en","source_url":"git://github.com/SocketCluster/socketcluster-client","tags":["javascript","websocket","realtime","client","socketcluster"],"install":[{"cmd":"npm install socketcluster-client","lang":"bash","label":"npm"},{"cmd":"yarn add socketcluster-client","lang":"bash","label":"yarn"},{"cmd":"pnpm add socketcluster-client","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required to run a complete SocketCluster application. The client connects to a server instance provided by this package.","package":"socketcluster-server","optional":true}],"imports":[{"note":"Since v10.0.0, `create` is the preferred named export for initiating a connection. The default export is often used but less precise.","wrong":"import socketClusterClient from 'socketcluster-client'; const socket = socketClusterClient.create(...);","symbol":"create","correct":"import { create } from 'socketcluster-client';"},{"note":"The primary socket class was renamed from `SCSocket` to `SCClientSocket` in v13.0.0 for clarity and consistency. Use `SCClientSocket` for type imports or direct instantiation.","wrong":"import { SCSocket } from 'socketcluster-client';","symbol":"SCClientSocket","correct":"import { SCClientSocket } from 'socketcluster-client';"},{"note":"The module's main export is often an object containing utility methods like `create`. In browsers, a global `socketClusterClient` object is available after loading the script.","wrong":"import socketClusterClient from 'socketcluster-client'; // Potentially not the default export, depending on bundler config.","symbol":"socketClusterClient (global/module object)","correct":"const socketClusterClient = require('socketcluster-client'); // CommonJS\n// Or in browser after script tag:\nconst socket = socketClusterClient.create(...);"}],"quickstart":{"code":"import { create } from 'socketcluster-client';\n\nconst socket = create({\n  hostname: 'localhost',\n  port: 8000,\n  autoConnect: true,\n  autoReconnectOptions: {\n    initialDelay: 1000,\n    randomness: 500,\n    multiplier: 1.2,\n    maxDelay: 10000\n  }\n});\n\n(async () => {\n  try {\n    await socket.listener('connect').once();\n    console.log('Socket connected successfully to server.');\n\n    // Transmit data to the server without expecting a response\n    socket.transmit('chatMessage', { user: 'developer', text: 'Hello SocketCluster!' });\n\n    // Invoke a remote procedure call (RPC) and await a response\n    const serverTime = await socket.invoke('getServerTime');\n    console.log('Server time received:', serverTime);\n\n    // Subscribe to a channel and consume messages\n    const myChannel = socket.subscribe('myPublicChannel');\n    await myChannel.listener('subscribe').once();\n    console.log('Successfully subscribed to channel: myPublicChannel');\n\n    // Publish a message to the channel\n    await myChannel.invokePublish('This is a message from the client.');\n    console.log('Published message to channel.');\n\n    // Consume messages from the channel using an async iterator\n    for await (const data of myChannel) {\n      console.log('Received channel message:', data);\n      // For demonstration, process one message then unsubscribe\n      break;\n    }\n    myChannel.unsubscribe();\n    console.log('Unsubscribed from channel.');\n\n  } catch (error) {\n    console.error('Socket error or connection failed:', error);\n  }\n\n  // Disconnect the socket after a short delay\n  setTimeout(() => {\n    socket.disconnect();\n    console.log('Socket disconnected.');\n  }, 5000);\n})();","lang":"typescript","description":"Demonstrates connecting to a SocketCluster server, transmitting data, invoking an RPC, subscribing to a channel, publishing to it, and consuming messages using async iterators."},"warnings":[{"fix":"Update all references from `SCSocket` to `SCClientSocket` in your code, including type imports and class instantiations.","message":"The `SCSocket` class was renamed to `SCClientSocket` for better clarity and consistency with server-side naming conventions.","severity":"breaking","affected_versions":">=13.0.0"},{"fix":"Review event handlers for 'authenticate' to ensure they correctly handle token changes and potential user session overrides, especially in multi-user or shared device environments.","message":"The 'authenticate' event now triggers whenever the `authToken` changes, not just on the initial authentication. This affects scenarios where a new user's token might override a previously logged-in user's token on the same client instance.","severity":"breaking","affected_versions":">=12.0.0"},{"fix":"Replace `socketClusterClient.connect(...)` with `socketClusterClient.create(...)` or `create(...)` if using named imports. While `connect` might still work, it is deprecated.","message":"The `socketCluster.connect(options)` method was renamed to `socketCluster.create(options)`. The `connect` alias is deprecated but still available.","severity":"breaking","affected_versions":">=10.0.0"},{"fix":"Update any references to `socketCluster.connections` to `socketCluster.clients`.","message":"The `socketCluster.connections` object/map was renamed to `socketCluster.clients`.","severity":"breaking","affected_versions":">=10.0.0"},{"fix":"Ensure that connection options (hostname, host, port) are correctly configured and mutually exclusive where required. Refer to the official documentation for valid combinations.","message":"Passing invalid combinations of `hostname`, `host`, and `port` arguments to `create()` will now throw an error, enforcing stricter configuration validation.","severity":"gotcha","affected_versions":">=11.0.0"},{"fix":"Avoid using event names that are internally reserved by SocketCluster for custom transmissions. If an error is triggered, rename your custom event.","message":"Attempting to emit a reserved event on the socket will now cause an error to be emitted on the socket itself. This prevents potential conflicts with internal SocketCluster protocols.","severity":"gotcha","affected_versions":">=13.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Change `socketClusterClient.connect(...)` to `socketClusterClient.create(...)`. The `connect` method was renamed in v10.0.0.","cause":"Using the deprecated `connect` method instead of `create`.","error":"TypeError: socketCluster.connect is not a function"},{"fix":"Ensure `<script type=\"text/javascript\" src=\"/socketcluster-client.js\"></script>` is present and accessible in your HTML, or use `import { create } from 'socketcluster-client';` (ESM) / `const { create } = require('socketcluster-client');` (CJS) at the top of your JavaScript file.","cause":"The `socketcluster-client` script tag was not loaded in the HTML, or the module was not correctly imported/required in a module environment.","error":"ReferenceError: socketClusterClient is not defined"},{"fix":"Update code to use `socketCluster.clients` instead of `socketCluster.connections`. This rename occurred in v10.0.0.","cause":"Attempting to access `socketCluster.connections` which was renamed.","error":"Error: Cannot read properties of undefined (reading 'connections')"},{"fix":"Rename the custom event you are trying to transmit to avoid conflict with SocketCluster's internal event names. This behavior changed in v13.0.0.","cause":"The client attempted to emit an event name that is reserved by SocketCluster internally.","error":"UnhandledPromiseRejectionWarning: Error: Socket emitted a reserved event"}],"ecosystem":"npm"}