This SDK provides a client to connect to Centrifugo or any Centrifuge-based server using pure WebSocket or one of the alternative transports (HTTP-streaming, SSE/EventSource, experimental WebTransport) from web browser, ReactNative, or NodeJS environments.
[!IMPORTANT]
This library behaves according to a common Centrifugo SDK spec. It's recommended to read that before starting to work with this SDK as the spec covers common SDK behavior - describes client and subscription state transitions, main options and methods. Then proceed with this readme for more specifics aboutcentrifuge-js.
The features implemented by this SDK can be found in SDK feature matrix.
centrifuge-jsv5.x is compatible with Centrifugo server v6, v5 and v4, and Centrifuge >= 0.25.0. For Centrifugo v2, Centrifugo v3 and Centrifuge < 0.25.0 you should usecentrifuge-jsv2.x.
getStateSDK can be installed via npm:
npm install centrifuge
And then in your project:
import { Centrifuge } from 'centrifuge';
In browser, you can import SDK from unpkg CDN (replace 5.0.0 with a concrete version number you want to use, see releases):
<script src="https://unpkg.com/centrifuge@5.0.0/dist/centrifuge.js"></script>
See also centrifuge-js on jsdelivr. Note that centrifuge-js browser builds target ES6.
By default, library works with JSON only, if you want to send binary payloads go to Protobuf support section to see how to import client with Protobuf support.
The basic usage example may look like this:
// Use WebSocket transport endpoint.
const centrifuge = new Centrifuge('ws://centrifuge.example.com/connection/websocket');
// Allocate Subscription to a channel.
const sub = centrifuge.newSubscription('news');
// React on `news` channel real-time publications.
sub.on('publication', function(ctx) {
console.log(ctx.data);
});
// Trigger subscribe process.
sub.subscribe();
// Trigger actual connection establishement.
centrifuge.connect();
Note, that we explicitly call .connect() method to initiate connection establishement with a server and .subscribe() method to move Subscription to subsribing state (which should transform into subscribed state soon after connection with a server is established). The order of .connect() and .subscribe calls does not actually matter here.
Centrifuge object and Subscription object are both instances of EventEmitter. Below we will describe events that can be exposed in detail.
This SDK supports several real-time transports.
WebSocket is the main protocol used by centrifuge-js to communicate with a server.
In a browser environment WebSocket is available globally, but if you want to connect from NodeJS env – then you need to provide WebSocket constructor to centrifuge-js explicitly. See below more information about this.
It's the only transport for which you can just use a string endpoint as first argument of Centrifuge constructor. If you need to use other transports, or several transports – then you should use Array<TransportEndpoint>.
In the quick start example above we used WebSocket endpoint to configure Centrifuge. WebSocket is the main transport – it's bidirectional out of the box.
In some cases though, WebSocket connection may not be established (for example, due to corporate firewalls and proxies). For such situations centrifuge-js offers several WebSocket fallback options based on HTTP:
These two transports use Centrifugo/Centrifuge own bidirectional emulation layer. See more details in introduction post. Bidirectional emulation must be first enabled on a server-side. See Centrifugo docs to find out how.
After enabling HTTP-streaming or SSE endpoints on a server side you can slightly change client initialization and point Javascript SDK to a list of endpoints and transports you want to use:
const transports = [
{
transport: 'websocket',
endpoint: 'ws://example.com/connection/websocket'
},
{
transport: 'http_stream',
endpoint: 'http://example.com/connection/http_stream'
},
{
transport: 'sse',
endpoint: 'http://example.com/connection/sse'
}
];
const centrifuge = new Centrifuge(transports);
centrifuge.connect()
In this case, client will try transports in order, one by one, during the initial handshake. Until success. Then will only use a successfully chosen transport during reconnects.
Supported transports are:
websockethttp_streamssesockjs - SockJS can also be used as a fallback in Centrifugo < v6, in Centrifugo v6 SockJS was removed and will be removed in centrifuge-js v6 too. Also, sticky sessions must be used on the backend in distributed case with it. See more details belowwebtransport - this SDK also supports WebTransport in experimental form. See details belowIf you want to use sticky sessions on a load balancer level as an optimimization for Centrifugal bidirectional emulation layer keep in mind that we currently use same-origin credentials policy for emulation requests in http_stream and sse transport cases. So cookies will only be passed in same-origin case. Please open an issue in case you need to configure more relaxed credentials. Though in most cases stickyness based on client's IP may be sufficient enough.
SockJS usage is DEPRECATED. Its support was removed in Centrifugo v6, and it will also be removed from this SDK in v6 release.
If you want to use SockJS you must also import SockJS client before centrifuge.js
<script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js" type="text/javascript"></script>
<script src="https://unpkg.com/centrifuge@5.0.0/dist/centrifuge.js" type="text/javascript"></script>
Or provide it explicitly as a dependency:
import { Centrifuge } from 'centrifuge'
import SockJS from 'sockjs-client'
const transports = [{
transport: "sockjs",
endpoint: "http://localhost:8000/connection/sockjs"
}];
const centrifuge = new Centrifuge(transports, {
sockjs: SockJS
})
Note, that in SockJS case endpoint starts with http://, not with ws:// as we used above when connecting to a pure WebSocket endpoint.
WebTransport is experimental and is only supported by Centrifugo at the moment (i.e. it's not available in Centrifuge library for Go out of the box).
Server must be additionally configured to work with WebTransport connections – see information in Centrifugo WebTransport docs.
Let's look at top-level API of Centrifuge client.
As we already showed above, we must call connect() method to make an actual connection
request to Centrifugo server:
const centrifuge = new Centrifuge('ws://centrifuge.example.com/connection/websocket');
centrifuge.connect();
connect() triggers an actual connection request to server.
As soon as connection is established and client successfully authenticated – connected event on Centrifuge object instance will be called.
It's possible to listen to this event by setting event listener function on connected event:
centrifuge.on('connected', function(ctx) {
// now client connected to Centrifugo and authenticated.
});
connecting event fired when Centrifuge object goes to connecting state. This may be called during initial connect, or after being connected due to temporary connection loss.
centrifuge.on('connecting', function(ctx) {
// do whatever you need in case of connecting to a server
});
disconnected event fired on Centrifuge object every time client disconnects for some reason. This can be terminal disconnect due to advice from a server or disconnect initiated by client-side.
centrifuge.on('disconnected', function(ctx) {
// do whatever you need in case of disconnect from server
});
state event is fired when client state changes. It provides both old and new state.
centrifuge.on('state', function(ctx) {
console.log('state changed from', ctx.oldState, 'to', ctx.newState);
});
In some cases you may need to disconnect your client from server, use .disconnect() method to do this:
centrifuge.disconnect();
After calling this client will not try to reestablish connection periodically. You must call .connect() method manually again.
Sometimes you need to publish into channel without actually being subscribed to it. In this case you can use publish method:
centrifuge.publish("channel", {"input": "hello"}).then(function(res) {
console.log('successfully published');
}, function(err) {
console.log('publish error', err);
});
This is only valid for Centrifuge server library for Go and does not work for Centrifugo server at the moment. send method allows sending asynchronous message from a client to a server.
centrifuge.send({"input": "hello"}).then(function(res) {
console.log('successfully sent');
}, function(err) {
console.log('send error', err);
});
rpc method allows to send rpc request from client to server and wait for data response.
centrifuge.rpc("my.method.name", {"input": "hello"}).then(function(res) {
console.log('rpc result', res);
}, function(err) {
console.log('rpc error', err);
});
Allows to get history from a server. This is a top-level analogue of Subscription.history method. But accepts a channel as first argument.
centrifuge.history("channel", {since: {offset: 0, epoch: "xyz"}, limit: 10}).then(function(resp) {
console.log(resp);
}, function(err) {
console.log('history error', err);
});
Allows to get presence info from a server. This is a top-level analogue of Subscription.presence method. But accepts a channel as first argument.
centrifuge.presence("channel").then(function(resp) {
console.log(resp);
}, function(err) {
console.log('presence error', err);
});
Allows to get presence stats from a server. This is a top-level analogue of Subscription.presenceStats method. But accepts a channel as first argument.
centrifuge.presenceStats("channel").then(function(resp) {
console.log(resp);
}, function(err) {
console.log('presence stats error', err);
});
Returns a Promise which will be resolved upon connection establishement (i.e. when Client goes to connected state).
setToken may be useful to dynamically change the connection token. For example when you need to implement login/logout workflow. See an example in blog post.
setData (since v5.5.0) allows setting connection data (some extra payload to deliver to the backend with connection request). This only affects the next connection attempt, not the current one. Note that if getData callback is configured, it will override this value during reconnects.
```
$ claude mcp add centrifuge-js \
-- python -m otcore.mcp_server <graph>