MCPcopy Index your code
hub / github.com/centrifugal/centrifuge-js

github.com/centrifugal/centrifuge-js @5.7.0

Chat with this repo
repository ↗ · DeepWiki ↗ · release 5.7.0 ↗ · + Follow
624 symbols 1,426 edges 35 files 192 documented · 31%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

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 about centrifuge-js.

The features implemented by this SDK can be found in SDK feature matrix.

centrifuge-js v5.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 use centrifuge-js v2.x.

Install

SDK 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.

Quick start

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.

Supported real-time transports

This SDK supports several real-time transports.

Websocket transport

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>.

HTTP-based WebSocket fallbacks

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:

  • websocket
  • http_stream
  • sse
  • sockjs - 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 below
  • webtransport - this SDK also supports WebTransport in experimental form. See details below

If 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.

Using SockJS

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 (experimental)

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.

Client API

Let's look at top-level API of Centrifuge client.

Client methods and events

connect method

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.

connected event

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

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

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

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);
});

disconnect method

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.

publish method

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);
});

send method

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

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);
});

history method

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);
});

presence method

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);
});

presenceStats method

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);
});

ready method

Returns a Promise which will be resolved upon connection establishement (i.e. when Client goes to connected state).

setToken method

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 method

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.

```

Extension points exported contracts — how you extend this code

IError (Interface)
Properties of an Error. [1 implementers]
src/client_proto.d.ts
SubscribeReplyOptions (Interface)
(no doc)
src/fakeServer.ts
MockItem (Interface)
(no doc)
src/shared_poll.test.ts
MockItem (Interface)
(no doc)
src/shared_poll.protobuf.test.ts
TypedEventEmitter (Interface)
(no doc)
src/types.ts
serverSubscription (Interface)
(no doc)
src/centrifuge.ts
IEmulationRequest (Interface)
Properties of an EmulationRequest. [1 implementers]
src/client_proto.d.ts
TransportEndpoint (Interface)
(no doc)
src/types.ts

Core symbols most depended-on inside this repo

ready
called by 214
src/centrifuge.ts
connect
called by 135
src/centrifuge.ts
subscribe
called by 128
src/subscription.ts
on
called by 65
src/types.ts
emit
called by 54
src/types.ts
track
called by 50
src/subscription.ts
newSharedPollSubscription
called by 48
src/centrifuge.ts
disconnect
called by 44
src/centrifuge.ts

Shape

Method 283
Class 120
Function 117
Interface 95
Enum 9

Languages

TypeScript100%

Modules by API surface

src/client_proto.d.ts126 symbols
src/centrifuge.ts106 symbols
src/subscription.ts98 symbols
src/types.ts62 symbols
src/client_proto.js42 symbols
src/fakeServer.ts19 symbols
src/transport_http_stream.ts14 symbols
src/fossil.ts13 symbols
src/transport_webtransport.ts11 symbols
src/transport_websocket.ts10 symbols
src/transport_sse.ts10 symbols
src/transport_sockjs.ts10 symbols

For agents

$ claude mcp add centrifuge-js \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page