Events

All changes to the chat state are exposed as events. When a new message is sent, a reaction is added, or any other action occurs, the client receives an event in real-time. You can also send custom events, enabling you to build your own pub/sub functionality on top of a channel.

Listening for Events

The code sample below shows how to listen to events:

channel.on("message.new", (event) => {
  console.log("received a new message", event.message.text);
});

channel.on("message.deleted", (event) => {
  console.log("message was deleted", event.message.id);
});

You can also listen to all events at once:

channel.on((event) => {
  console.log("event", event);
  console.log("channel.state", channel.state);
});

Event Types

There are different type of events

  • User level/connection level events. You always receive these events.
  • Notification events you receive if you are a member of the channel
  • Channel level events you receive if you are watching the channel
  • User presence events are sent when you specify presence=true
  • Custom events. Your own pub/sub on top of the chat channel.

The example below shows how to watch a channel and enable user presence events. You can also watch channels and enable user presence when using query channels. See these links for more details on user presence, watching and query channels.

// Watch a channel with presence enabled to receive user presence events
const channel = client.channel("messaging", "my-conversation-123", {
  members: ["john", "jack"],
});

const state = await channel.watch({ presence: true });

// Listen for user presence changes
channel.on("user.presence.changed", (event) => {
  console.log(
    `${event.user.name} is now ${event.user.online ? "online" : "offline"}`,
  );
});

Connection Events

The official SDKs make sure that a connection to Stream is kept alive at all times and that chat state is recovered when the user’s internet connection comes back online. Your application can subscribe to changes to the connection using client events.

client.on("connection.changed", (e) => {
  if (e.online) {
    console.log("the connection is up!");
  } else {
    console.log("the connection is down!");
  }
});

Stop Listening for Events

It is a good practice to unregister event handlers once they are not in use anymore. Doing so will save you from performance degradations coming from memory leaks or even from errors and exceptions (i.e. null pointer exceptions)

// remove the handler from all client events
// const myClientEventListener = client.on('connection.changed', myClientEventHandler)
myClientEventListener.unsubscribe();

// remove the handler from all events on a channel
// const myChannelEventListener = channel.on('connection.changed', myChannelEventHandler)
myChannelEventListener.unsubscribe();

Custom Events

Custom events allow you to build your own pub/sub functionality on top of a channel. You can send any event with custom data and have it delivered to all users watching the channel.

To a channel

Users connected to a channel, either as a watcher or member, can send custom events and have them delivered to all users watching the channel.

var channelEvent = new Event { Type = "friendship_request", UserId = serverUser.Id };
channelEvent.SetData("text", "Hey there, long time no see!");
await eventClient.SendEventAsync("channel-type", "channel-id", channelEvent);

Custom events are enabled by default on all channel types, you can disable them using the Dashboard or the API the same way as you would manage other channel features (ie. replies, URL previews, …)

Permissions

Like every client-side API request, sending a custom event includes a permission check. By default users that can read messages on a channel can also send custom events. Check the Auth & Permission section to find out more about how permissions can be customized for your application.

Keep in mind a clever user can send their own custom events. We recommend using the type attribute or custom data on the event to limit the kinds of events that are displayed to the recipient to ones that are safe e.g. if a bad actor sends a “password reset” or other malicious events, your client app should just ignore it.

To a user

This allows you to send custom events to a connected user. The event is delivered to all connected clients for that user.

It is only available with server-side authentication. A copy of the event is sent via web-hooks if it is enabled.

var customEvent = new UserCustomEvent { Type = "friendship_request" };
customEvent.SetData("text", "Tommaso wants to be your friend");
await eventClient.SendUserCustomEventAsync(user.Id, customEvent);
nametypedescriptiondefaultoptional
targetUserIDstringtarget user ID-
dataobjectevent to be sent-
data.typestringtype of the event-

If the user doesn’t exist, a 404 Not Found error is returned.

The type of the event shouldn’t contain any . character otherwise a 400 Bad Request error is returned. This is a character used for built-in events, see the Built-in Events section below for more details.

Event Object

nametypedescriptiondefaultoptional
cidstringChannel ID
typestringEvent type
messageobjectMessage Object
reactionobjectReaction Object
channelobjectChannel Object
memberobjectUser object for the channel member that was added/removed
userobjectUser object of the current user
meobjectUser object of the health check user
total_unread_countintthe number of unread messages for current user
watcher_countintNumber of users watching this channel

Built-in Events

The table below shows an overview of all built-in events:

EventTriggerRecipientsType
channel.deletedwhen a channel is deletedclients watching the channelchannel event
channel.hiddenwhen a channel is marked as hiddenclients from the user that marked the channel as hidden (see hiding channels)channel event
channel.truncatedwhen a channel’s history is truncatedclients watching the channelchannel event
channel.updatedwhen a channel is updatedclients watching the channelchannel event
channel.visiblewhen a channel is made visibleclients from the user that marked the channel as visible (see hiding channels)channel event
connection.changedwhen the state of the connection changedlocal eventclient event
connection.recoveredwhen the connection to chat servers is back onlinelocal eventclient event
health.checkevery 30 seconds to confirm that the client connection is still aliveall clientsclient event
member.addedwhen a member is added to a channelclients watching the channelchannel event
member.removedwhen a member is removed from a channelclients watching the channelchannel event
member.updatedwhen a channel member is updated (promoted to moderator/accepted/rejected the invite)clients watching the channelchannel event
message.deletedwhen a message is deletedclients watching the channelchannel event
message.newwhen a new message is added on a channelclients watching the channelchannel event
message.readwhen a channel is marked as readclients watching the channelchannel event
message.updatedwhen a message is updatedclients watching the channelchannel event
notification.added_to_channelwhen the user is added to the list of channel membersclients from the user added that are not watching the channelnotification event
notification.channel_deletedwhen a channel is deletedclients from members that are not watching the channelnotification event
notification.channel_mutes_updatedwhen a channel is mutedclients from the user that muted the channelnotification event
notification.channel_truncatedwhen a channel’s history is truncatedclients from members that are not watching the channelnotification event
notification.invite_acceptedwhen the user accepts an inviteclients from the user invited that are not watching the channelnotification event
notification.invite_rejectedwhen the user rejects an inviteclients from the user invited that are not watching the channelnotification event
notification.invitedwhen the user is invited to join a channelclients from the user invited that are not watching the channelnotification event
notification.mark_readwhen the total count of unread messages (across all channels the user is a member) changesclients from the user with the new unread countnotification event
notification.mark_unreadwhen the user marks a message as unreadclients from the user with the new unread countnotification event
notification.message_newwhen a message is added to a channelclients that are not currently watching the channelnotification event
notification.mutes_updatedwhen the user mutes are updatedclients from the user that updated the list of mutesnotification event
notification.removed_from_channelwhen a user is removed from the list of channel membersclients from the user removed that are not watching the channelnotification event
reaction.deletedwhen a message reaction is deletedclients watching the channelchannel event
reaction.newwhen a message reaction is addedclients watching the channelchannel event
reaction.updatedwhen a message reaction is updatedclients watching the channelchannel event
typing.startwhen a user starts typingclients watching the channelchannel event
typing.stopwhen a user stops typingclients watching the channelchannel event
user.bannedwhen the user is bannedclients for the banned userclient event
user.deletedwhen a user is deletedclients subscribed to the user statususer presence event
user.messages.deletedwhen the user’s messages are deletedclients for the banned userclient event
user.messages.deletedwhen the user’s messages are deletedclients watching the channel where the user was bannedchannel event
user.presence.changedwhen a user status changes (eg. online, offline, away, etc.)clients subscribed to the user statususer presence event
user.unbannedwhen the user ban is liftedclients for the banned userclient event
user.updatedwhen a user is updatedclients subscribed to the user statususer presence event
user.watching.startwhen a user starts watching a channelclients watching the channelchannel event
user.watching.stopwhen a user stops watching a channelclients watching the channelchannel event