PlayMesh/Docs
HomeGitHubnpm

Client API

Complete reference for @playmesh/client — connecting, emitting, and receiving events.

PlayMeshClient

Import from @playmesh/client.

Constructor

import { PlayMeshClient } from '@playmesh/client';
const client = new PlayMeshClient(options: PlayMeshClientOptions);
Method / PropertyDescriptionReturns
urlServer URL. e.g. "https://game.example.com"string
authAuth payload for the server's authenticate hook, or a function called on every connection attempt (useful for token refresh).object | () => object
socketOptions forwarded to the underlying Socket.IO client.Partial<SocketOptions>

Connection

Method / PropertyDescriptionReturns
connect()Connect and authenticate. Resolves with SessionInfo once the server establishes the session.Promise<SessionInfo>
disconnect()Disconnect from the server.void
connectedWhether the client is currently connected.boolean
const session = await client.connect();
// session: { id: string, userId: string, instances: string[] }

console.log('Connected as', session.userId);
console.log('Instances:', session.instances);

client.disconnect();

Session

Method / PropertyDescriptionReturns
sessionCurrent session info. Updated automatically as instances change.SessionInfo | undefined
instancesInstance paths ("domainId/instanceId") this session belongs to.string[]

Events

Method / PropertyDescriptionReturns
emit(event, payload?)Send an event to the server. Throws if not connected.void
on(event, handler)Listen for an event from the server.this
off(event, handler)Remove a listener.this
client.on('chat', payload => {
  const { sender, message } = payload as { sender: string; message: string };
  appendMessage(`${sender}: ${message}`);
});

client.emit('move', { x: 100, y: 250 });

const handler = (payload: unknown) => { /* ... */ };
client.on('update', handler);
client.off('update', handler);

Connection lifecycle

Method / PropertyDescriptionReturns
onDisconnect(handler)Called when the connection drops. Receives the reason string.this
onReconnect(handler)Called when the connection is automatically re-established.this
onError(handler)Called when the server reports an error.this
client.onDisconnect(reason => {
  console.warn('Disconnected:', reason);
  showReconnectUI();
});

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

client.onError(error => {
  // { scope: 'connection' | 'event', event?: string, message: string }
  console.error('Server error:', error.message);
});

Authentication

// Static token
const client = new PlayMeshClient({
  url: 'https://game.example.com',
  auth: { token: localStorage.getItem('jwt') },
});

// Dynamic — refreshed on each reconnect
const client = new PlayMeshClient({
  url: 'https://game.example.com',
  auth: async () => ({ token: await authService.getToken() }),
});

Instance membership

The client automatically maintains client.instances as the server sends playmesh:joined and playmesh:left events.
Instance membership is controlled entirely by the server. The client cannot directly request to join or leave instances.

Types

interface SessionInfo {
  id: string;
  userId: string;
  instances: string[];  // "domainId/instanceId" paths
}

interface ServerError {
  scope: 'connection' | 'event';
  event?: string;
  message: string;
}

Full example

game-client.ts
import { PlayMeshClient } from '@playmesh/client';

const client = new PlayMeshClient({
  url: import.meta.env.VITE_SERVER_URL,
  auth: async () => ({ token: await authService.getAccessToken() }),
});

client.on('world-state', payload => gameRenderer.updateWorld(payload));
client.on('player-joined', payload => gameRenderer.spawnPlayer(payload.userId));
client.on('player-left', payload => gameRenderer.removePlayer(payload.userId));
client.onDisconnect(() => gameRenderer.showDisconnectedOverlay());
client.onReconnect(() => gameRenderer.hideDisconnectedOverlay());

export async function startGame() {
  const session = await client.connect();
  gameRenderer.setLocalPlayerId(session.userId);
}

export const movePlayer = (x: number, y: number) => client.emit('move', { x, y });
export const sendChat = (message: string) => client.emit('chat', { message });