Client SDKConnection Lifecycle

Connection Lifecycle & Reconnection

Handle the various states of a room connection.

Leaving a Room

Disconnect from the room. Use consented: true (default) for intentional leaves, or false to simulate an unexpected disconnect.

client.ts
// consented leave
room.leave();
 
// force unconsented leave
room.leave(false);

Backend: Use Room → On Leave to handle client disconnection.

Listening for the leave event:

client.ts
room.onLeave((code) => {
  console.log("client left the room");
});

Possible closing codes and their meaning:

  • 1000 - Regular socket shutdown
  • Between 1001 and 1015 - Abnormal socket shutdown
  • Between 4000 and 4010 - Reserved by the framework (CONSENTED, SERVER_SHUTDOWN, FAILED_TO_RECONNECT, …)
  • Between 4011 and 4999 - Custom application close code (See more details)

Automatic Reconnection

The SDK automatically attempts to reconnect when the connection is unexpectedly dropped.

⚠️

Automatic reconnection only triggers if the room has been connected for at least minUptime milliseconds. This threshold prevents reconnection loops for rooms that fail immediately after joining.

On Drop Event

Triggered when the connection is unexpectedly dropped. The SDK will automatically attempt to reconnect.

client.ts
room.onDrop((code, reason) => {
  console.log("connection dropped, attempting to reconnect...");
  console.log("code:", code, "reason:", reason);
});

The onDrop event is different from onLeave. While onLeave is triggered when the client intentionally leaves or the connection is permanently closed, onDrop indicates a temporary disconnection where reconnection will be attempted.

Close codes that trigger onDrop:

  • 1005 - No status received
  • 1006 - Abnormal closure
  • 1001 - Going away
  • 4010 - May try reconnect

On Reconnect Event

Triggered when the client successfully reconnects after a connection drop. While disconnected, your room.send() calls will be queued and sent to the server when the client reconnects. The maximum number of queued messages is configurable using room.reconnection.maxEnqueuedMessages.

client.ts
room.onReconnect(() => {
  console.log("successfully reconnected to the room!");
});

Reconnection Options

You may configure the reconnection behavior using room.reconnection.

Reconnection config options

OptionDefaultDescription
enabledtrueSet to false to disable automatic reconnection entirely
maxRetries15Maximum reconnection attempts
minDelay100Minimum delay between attempts (ms)
maxDelay5000Maximum delay between attempts (ms)
minUptime5000Minimum room uptime before reconnection is allowed (ms)
delay100Initial delay between attempts (ms)
maxEnqueuedMessages10Maximum buffered messages during reconnection
backoffexponentialDelay calculation function

Status properties (read-only)

PropertyTypeDescription
isReconnectingbooleanWhether currently reconnecting
retryCountnumberCurrent reconnection attempt count
enqueuedMessagesarrayMessages buffered while disconnected (count: .length)

Customizing reconnection behavior:

client.ts
const room = await client.joinOrCreate("battle");
 
// Customize reconnection options
room.reconnection.maxRetries = 10;
room.reconnection.maxDelay = 10000; // 10 seconds max delay
room.reconnection.minUptime = 3000; // Allow reconnection after 3 seconds

Custom backoff function:

client.ts
room.reconnection.backoff = (attempt: number, delay: number) => {
  return Math.floor(Math.pow(2, attempt) * delay);
};

Manual Reconnection

For more control, you can manually reconnect using a cached reconnection token. Because this method returns a new room instance on the client, you must reattach all event listeners to the room after reconnecting.

  • You must store/cache the room.reconnectionToken from an active room connection.
  • The server needs to call .allowReconnection() for that client.
client.ts
try {
  const room = await client.reconnect(cachedReconnectionToken);
  console.log("joined successfully", room);
 
} catch (e) {
  console.error("join error", e);
}

Error Handling

Listen for errors that occur in the room.

client.ts
room.onError((code, message) => {
  console.log("oops, error occurred:");
  console.log(message);
});

Removing Listeners

Remove all event listeners from the room (onJoin, onStateChange, onError, onLeave, onReconnect, onDrop, registered message handlers, and schema callbacks):

client.ts
room.removeAllListeners();

The SDK calls removeAllListeners() automatically when the room is left. You only need it to detach early, e.g. when tearing down a UI screen while staying connected.