Supporters
JOIN MY SPONSORS

Receiving Messages

Use .on() to listen for incoming messages. The listener API supports simple string matching, custom type routing, filter functions, and wildcards. For convenience, object-based messages are spread to the top level of the event for easy access.

Basic Messages

The 'message' event fires for every incoming message that doesn't have a event-level type field:

message.js
// listen for all messages
channel.on('message', ({ message, uid, alias, date }) => {
  console.log(`${alias}: ${message}`)
})

The event includes message (the payload), uid (sender ID), alias (display name, if set), and date (server timestamp).

Type Routing

When a message includes a type field, you can listen for that type directly. The message properties are spread to the top level of the event for convenience:

typed.js
// route by message type
channel.on('chat', ({ text, uid }) => {
  console.log(`[${uid}] ${text}`)
})

channel.on('move', ({ x, y, uid }) => {
  moveCursor(uid, x, y)
})

// these fire when someone sends:
channel.send({ type: 'chat', text: 'hello!' })
channel.send({ type: 'move', x: 100, y: 200 })

This is the recommended pattern for apps that send different kinds of messages. Each type gets its own clean handler — no switch statements needed.

Filter Functions

For more complex routing, pass a function as the first argument. The listener only fires when your function returns true:

filter.js
// use a filter function for complex routing
channel.on(
  (e) => e.type === 'chat' && e.text?.includes('urgent'),
  ({ text, uid }) => {
    alert(`Urgent from ${uid}: ${text}`)
  }
)

// filter by sender
channel.on(
  (e) => e.uid === 'abc123',
  ({ message }) => console.log('from my friend:', message)
)

This is powerful for cross-cutting concerns — match on any combination of type, sender, content, or custom fields.

Wildcard

The '*' event catches everything — messages, joins, leaves, errors, and custom types:

wildcard.js
// catch ALL events — messages, joins, leaves, errors, custom types
channel.on('*', (event) => {
  console.log('event:', event)
})

Useful for logging, debugging, or building middleware-style pipelines.

Multiple Listeners

You can register multiple listeners for the same event. They all fire independently:

multiple.js
channel
  .on('chat', logToConsole)
  .on('chat', updateUI)
  .on('chat', playNotificationSound)

Use .remove(type, listener) to unregister a specific listener.


Next: Join & Leave — track users entering and leaving your channels.