Send and receive arbitrary data by using custom events
Custom events allow a way for developers to send a payload with arbitrary data to all other participants in the Space. A participant can publish a custom event and expect other participants in the Space to receive a custom event with the same payload. There is no stateful information in the custom event as only participants connected to the active session can send and receive events.
To publish a custom event, the payload must be a string and must not be greater than 4MB in size. The sender must also have a publisher
role in their JWT (the JWTs assume this role by default). Custom events are rate limited at 1 request per second for each sender.
Although custom events require a string payload, developers may convert their data into a string on the sender side and convert the string back to its original form on the receiver side. This makes custom events suitable for many different use cases with structured data, such as gestures, notifications, or chat messages.
Refer to the web SDK documentation to learn more about the API.
import { Space } from "@mux/spaces-web";
const space = new Space(JWT);
// Join the Space and get the LocalParticipant
const localParticipant = await space.join();
// Form a string payload
const payload = JSON.stringify({
message: "🚀",
});
// Publish the CustomEvent as the LocalParticipant
// If successful, a SpaceEvent.ParticipantCustomEventPublished event is emitted to the Space
// and a ParticipantEvent.CustomEventPublished event is emitted to the LocalParticipant
try {
await localParticipant.publishCustomEvent(payload);
} catch (error) {
// Handle errors
}
Developers can listen to the Space or the sender to know when a custom event has been published.
import { Space, SpaceEvent, ParticipantEvent } from "@mux/spaces-web";
const space = new Space(JWT);
// Join the space
const localParticipant = await space.join();
// Listen to the Space for a SpaceEvent.ParticipantCustomEventPublished event
// The first argument in the event handler is the sender, and the second argument is the CustomEvent
space.on(SpaceEvent.ParticipantCustomEventPublished, (participant, event) => {
// Handle event
const payload = event.payload;
});
// Listen to the sender for a ParticipantEvent.CustomEventPublished event
// The argument in the event handler is the CustomEvent
space.on(SpaceEvent.ParticipantJoined, (participant) => {
participant.on(ParticipantEvent.CustomEventPublished, (event) => {
// Handle event
const payload = event.payload;
});
});
localParticipant.on(ParticipantEvent.CustomEventPublished, (event) => {
// Handle event
const payload = event.payload;
});