{"id":10747,"library":"diffusion","title":"Diffusion JavaScript Client","description":"The Diffusion JavaScript Client is a comprehensive library for interacting with Diffusion servers (on-premise or Diffusion Cloud) from both browser and Node.js environments. It enables real-time data streaming, pub/sub messaging, and management of topic trees over WebSockets or HTTP. Currently stable at version 6.12.1, the library typically sees regular updates, with minor versions being backward-compatible, while major versions (e.g., v5 to v6) often introduce breaking changes that require client application updates. Key differentiators include its robust support for diverse topic types, built-in TypeScript definitions, and modular bundles for optimized loading, alongside its use of Promises for asynchronous operations. It is designed for applications requiring high-performance, secure, and scalable real-time data distribution infrastructure.","status":"active","version":"6.12.1","language":"javascript","source_language":"en","source_url":null,"tags":["javascript","diffusion","cloud","websockets","data","typescript"],"install":[{"cmd":"npm install diffusion","lang":"bash","label":"npm"},{"cmd":"yarn add diffusion","lang":"bash","label":"yarn"},{"cmd":"pnpm add diffusion","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for client-side message compression in browser environments. Not needed in Node.js as it uses native zlib.","package":"browserify-zlib","optional":true},{"reason":"Recommended for ESM/CommonJS web application frameworks (like Vue/Vite) to polyfill Node.js APIs (e.g., zlib, Buffer) if client-side compression or binary data handling is needed.","package":"vite-plugin-node-polyfills","optional":true}],"imports":[{"note":"ESM import for TypeScript and modern JavaScript. CommonJS `require` is also supported but not idiomatic for new projects shipping types.","wrong":"const diffusion = require('diffusion');","symbol":"diffusion","correct":"import * as diffusion from 'diffusion';"},{"note":"The `connect` function is a named export from the `diffusion` module. While `import * as diffusion from 'diffusion';` is common, direct named imports are also possible.","wrong":"import connect from 'diffusion';","symbol":"connect","correct":"import { connect } from 'diffusion';"},{"note":"The `Session` interface/type is crucial for type-checking when working with connected Diffusion sessions. The primary `diffusion` object itself is not a class to be instantiated with `new`.","symbol":"Session","correct":"import { Session } from 'diffusion';"}],"quickstart":{"code":"import * as diffusion from 'diffusion';\n\nasync function runDiffusionClient() {\n  const host = process.env.DIFFUSION_HOST ?? 'ws://localhost:8080';\n  const principal = process.env.DIFFUSION_PRINCIPAL ?? 'admin';\n  const credentials = process.env.DIFFUSION_CREDENTIALS ?? 'password';\n  const topicPath = 'my/topic/path';\n\n  let session: diffusion.Session | undefined;\n  try {\n    session = await diffusion.connect({\n      host: host,\n      principal: principal,\n      credentials: credentials,\n      // secure: true // Uncomment for WSS connections\n    });\n    console.log(`Connected to Diffusion server: ${session.sessionId}`);\n\n    // Create a value stream for a JSON topic\n    session.addStream(topicPath, diffusion.datatypes.json()).on(\n      'value', \n      (topic, spec, newValue, oldValue) => {\n        console.log(`Update for ${topic}: ${JSON.stringify(newValue?.get())}`);\n      }\n    );\n\n    // Subscribe to the topic\n    await session.select(topicPath);\n    console.log(`Subscribed to topic: ${topicPath}`);\n\n    // Example: Publish a JSON value (requires appropriate permissions on the Diffusion server)\n    const topicControl = session.topicUpdate.createUpdateContext();\n    await topicControl.set(\n      topicPath,\n      diffusion.datatypes.json(),\n      diffusion.datatypes.json().newValue({ message: 'Hello, Diffusion!', timestamp: Date.now() })\n    );\n    console.log('Published a message to the topic.');\n\n    // Keep the session open for a bit to receive updates\n    await new Promise(resolve => setTimeout(resolve, 10000));\n\n  } catch (error: any) {\n    console.error('Diffusion connection or operation failed:', error.message || error);\n  } finally {\n    if (session) {\n      await session.close();\n      console.log('Diffusion session closed.');\n    }\n  }\n}\n\nrunDiffusionClient();","lang":"typescript","description":"This quickstart demonstrates how to establish a connection to a Diffusion server, subscribe to a JSON topic, and receive real-time updates. It also shows how to publish a message to the topic, handling connection errors and ensuring proper session closure."},"warnings":[{"fix":"Review the official Diffusion documentation's 'Upgrading from version 5.x to version 6.0' guide. Recompile server-side components. Refactor client-side code to use the Unified API and supported topic types.","message":"Upgrading from Diffusion JavaScript client v5.x to v6.x involves significant breaking changes. The 'Classic API' has been entirely removed; applications must migrate to the 'Unified API'. Additionally, several legacy topic types (e.g., Paged string, Paged record, Protocol buffer, Service topics) are no longer supported. Server-side components compiled against older versions may also require recompilation.","severity":"breaking","affected_versions":">=6.0"},{"fix":"For browser applications, include `browserify-zlib-0.2.0.js` in your build process or use a polyfill library if working within a modern framework. For Node.js, no action is typically needed.","message":"Client-side message compression via zlib is not included by default in browser bundles to reduce size. If compression is desired in a browser environment, you must explicitly include `browserify-zlib-0.2.0.js` or polyfill zlib (e.g., via `vite-plugin-node-polyfills` in frameworks like Vue/Vite). Node.js environments do not require this, as zlib is a standard module.","severity":"gotcha","affected_versions":">=6.1"},{"fix":"Thoroughly test topic selectors in both client and server environments. Simplify regular expressions where possible or use exact topic paths to minimize discrepancies. Consult Diffusion documentation on regular expression behavior.","message":"Topic selectors, which can include regular expressions, may behave differently on the Diffusion client and server due to different underlying regular expression engines. This can lead to unexpected subscription or topic selection behavior.","severity":"gotcha","affected_versions":">=5.0"},{"fix":"Design client applications to gracefully handle disconnections and reconnections. Implement logic for re-establishing subscriptions, re-creating topics, and re-registering handlers upon reconnection.","message":"Restarting a Diffusion Cloud service (e.g., for updates or maintenance) results in the loss of all transient topic information (tree structure, topic state) and subscription data. All connected clients are disconnected. While security and authentication information persists, clients must reconnect, re-register handlers, re-create topics, and resubscribe.","severity":"gotcha","affected_versions":">=5.0"},{"fix":"Remove any usage of the `ServerStatisticsConfig` API or `server-statistics` elements from `Statistics.xml` in your Diffusion server configuration and custom applications.","message":"The `ServerStatisticsConfig` API and related elements in `Statistics.xml` are deprecated and no longer have any function as of Diffusion v6.0.","severity":"deprecated","affected_versions":">=6.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Verify the `host`, `port`, `principal`, and `credentials` parameters in your `diffusion.connect()` call. Ensure the Diffusion server is running and network accessible. Check server logs for connection attempts and authentication failures.","cause":"Incorrect host, port, principal, or credentials provided during `diffusion.connect()`, or the Diffusion server is not running or accessible.","error":"Failed to connect"},{"fix":"When using modular bundles, ensure that all required feature bundles are dynamically loaded *after* the `diffusion-core.js` bundle if you need features beyond basic subscription and value streams. Alternatively, use the full `diffusion.js` bundle if bundle size is not a critical concern.","cause":"Attempting to use a Diffusion client feature (e.g., advanced topic management) that has not been loaded when using the `modular/diffusion-core.js` bundle, which provides only core features like value streams and topic subscription.","error":"Error being thrown (when accessing feature after using modular/diffusion-core.js)"},{"fix":"Log the `SessionError` details, including the message and any `cause` property. Consult the Diffusion server logs for more information about the underlying issue. It is often appropriate to close the current session and attempt to reconnect.","cause":"A generic error reported asynchronously from a service call, indicating an unexpected server-side condition that the application typically cannot directly recover from.","error":"SessionError: <error message>"}],"ecosystem":"npm"}