How to Send and Receive Custom Events

This guide covers how to send and receive Custom Events with the Vonage Client SDK. Before you begin, make sure you added the SDK to your app, created a Session (Android, iOS, JS), and joined a Conversation.

Custom Events are Events that have custom data and are stored in a Conversation unlike ephemeral Events. Therefore when you get a Conversation's Events they will be returned. You can also filter by your Custom Event type when getting a Conversation's Events.

Custom Events are delivered to all App Members in a Conversation. They are best suited for implementing custom actions for the Conversation, such as a poll.

Sending Custom Events

Given a Conversation ID, you can send a custom Event. You must give your Event a type. The type must:

  • begin with custom:
  • be a total of 100 characters or less
  • only contain alphanumeric, :, -, and _ characters For example, a poll could use the types custom:poll:question and custom:poll:response.

The custom data must not exceed 4096 bytes. It is recommended that you use JSON for your custom data but you can send anything here.

const customData = {
    key1: "value 1",
    key2: "value 2"
};

client.sendCustomEvent(conversationId, "custom:my-event", customData)
    .then(timestamp => {
        console.log("Successfully sent custom event at ", timestamp);
    }).catch(error => {
        console.error("Error sending custom event: ", error);
    });

Receiving Custom Events

You can receive all Conversation Events in your application by setting up an Event Listener/Delegate Function. Here you can check the kind of incoming Event. Further filtering of the incoming Custom Event can be done on the eventType.

client.on("conversationEvent", event => {
    switch (event.kind) {
        case "custom":
            handleCustomEvent(event); // event.eventType: custom event type
            break;
    };
});