Guide

Peer

Peer object allows easily interacting with connected clients.


Websocket hooks accept a peer instance as their first argument. You can use peer object to get information about each connected client or send a message to them.

You can safely log a peer instance to the console using console.log it will be automatically stringified with useful information including the remote address and connection status!

Properties

peer.url

Request http url during upgrade. You can use it to do actions based on path and search params.

peer.headers

Request http headers during upgrade. Youb can use it to do authentication and access upgrade headers.

peer.addr

The IP address of the client.

peer.id

A unique id assigned to the peer.

peer.readyState

Client connection status (might be undefined)

Read more in readyState in MDN.

Methods

peer.send(message, compress)

Send a message to the connected client.

peer.subscribe(channel)

Join a broadcast channel.

Read more in Guide > Pubsub.

peer.unsubscribe(channel)

Leave a broadcast channel.

Read more in Guide > Pubsub.

peer.publish(channel, message)

broadcast a message to the channel.

Read more in Guide > Pubsub.

peer.close(code?, number?)

Gracefully closes the connection.

Here is a list of close codes:

  • 1000 means "normal closure" (default)
  • 1009 means a message was too big and was rejected
  • 1011 means the server encountered an error
  • 1012 means the server is restarting
  • 1013 means the server is too busy or the client is rate-limited
  • 4000 through 4999 are reserved for applications (you can use it!)

To close the connection abruptly, use peer.terminate().

peer.terminate()

Abruptly close the connection.

To gracefully close the connection, use peer.close().