Publishing Events

If you are connected with the "publish" permission, you are able to send events to conencted rooms. Publishing an event is a way of transmitting data to interested parties.

Events can be published from both client-side and server-side applications.

Client-Side Publishing

Client event publishing occurs when a connection with the "publish" permission emits an event using the client library SDK.

const myRoom = await relayBox.join('myRoom');

// The name of the event to publish
const event = 'eventOne';

// The data to publish to the room
const data = {
  randomData: true
};

const data = await myRoom.publish(event, data);

In the code snippet above, we joined a room called "myRoom" and published an event "eventOne". All connections in the room subscribed to either this specific event or to all room events will receive this data in real-time.

Publishing events is an asynchronous operation, and failed events will throw an exception, which can be handled using try/catch syntax.

Server-Side Publishing

Along with client-side events, server-side applications can also publish events in the same way. Because a server-side process isn't able to physically "join" a room the same way a client-side connection does, the syntax is slightly different but the core concept remains the same.

const relayBox = new RelayBox({
  apiKey: 'xxxxxx:xxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxx'
});

// The name of the room to publish to
const room = 'myRoom';

// The name of the event to publish
const event = 'eventOne';

// The data to publish to the room
const data = {
  randomData: true
};

// Publish data to event subscribers
const response = await relayBox.publish(room, event, data);

If the API key has the necessary permissions, the event will be published successfully.

The "Publish" Permission

The publish permission works the same on both the client and server sides. The message initiator requires the "publish" permission, either globally or for the individual room, in order to transmit data to a room. To learn more about permissions, please see the Access Controls section.

    On this page