PlayMesh/Docs
HomeGitHubnpm

Connection & Reconnection

The client connection lifecycle - connect, auto-reconnect, token refresh, errors, and kicks.

Connecting

connect() resolves once the server has fully established the session - after your authentication hook ran and admission placed the session in its initial instances. It rejects if the server refuses the connection, and throws if the client is already connected or connecting.
const client = new PlayMeshClient({ url, auth: { token } });

try {
  const session = await client.connect();
  // session: { id, userId, instances }
} catch (error) {
  // Auth failure or unreachable server: "Connection failed: ..."
}
disconnect() tears the connection down and clears client.session. A later connect() starts fresh.

Automatic reconnection

Reconnection is handled by the underlying Socket.IO client and is on by default. Tune it through the socket option:
const client = new PlayMeshClient({
  url: 'https://game.example.com',
  socket: {
    reconnection: true,
    reconnectionDelay: 1000,
    reconnectionDelayMax: 5000,
    reconnectionAttempts: Infinity,
  },
});
On every reconnect the server re-authenticates and re-admits the session, and the client re-seeds its instance list, presence, and synced-state replicas from the new join snapshots.

Token refresh

Pass auth as a function and it is re-evaluated on every connection attempt - so an expired token is refreshed before each reconnect instead of failing the handshake:
const client = new PlayMeshClient({
  url: 'https://game.example.com',
  auth: async () => ({ token: await authService.getToken() }),
});

Lifecycle handlers

client.onDisconnect(reason => {
  showReconnectOverlay(reason);
});

client.onReconnect(() => {
  hideReconnectOverlay();
});

client.onError(error => {
  // { scope: 'connection' | 'event' | 'join' | 'chat',
  //   event?, instance?, message }
  if (error.scope === 'connection') showAuthError(error.message);
});

client.onKick(reason => {
  // Told why, then force-disconnected - no automatic reconnect makes sense here
  showKickedScreen(reason);
});
error.scope tells you what failed: connection (setup/auth), event (an emit was rejected server-side), join (a client.join() was vetoed - error.instance names the instance), or chat (a message was blocked).

Reconnection with signing

With signing enabled, every connection gets a fresh session nonce from the server. After a reconnect the client waits for the new nonce before sending signed events; events queued for the old connection are dropped and reported via onError rather than replayed. See Auth & Admission for the full signing model.