More

Connections

Connections represent client connections to your actor. They provide a way to handle client authentication, manage connection-specific data, and control the connection lifecycle.


Parameters

When clients connect to an actor, they can pass connection parameters that are handled during the connection process.

For example:

interface ConnectionParams {
  authToken: string;
}

class Example extends Actor<State, ConnectionParams> {
  _onBeforeConnect(opts: OnBeforeConnectOptions<this>) {
    const authToken = opts.parameters.authToken;
    // ...
  }
}

Connection State

The data returned from _onBeforeConnect is used as the initial state of the connection. The connection state can be accessed in any actor method using connection.state.

For example:

interface ConnectionState {
  userId: string;
  role: string;
}

class Example extends Actor<State, ConnectionState> {
  // The data returned from `_onBeforeConnect` will be assigned to the connection's state
  _onBeforeConnect(opts: OnBeforeConnectOptions<this>): ConnectionState {
    return { userId: 123, role: 'admin' };
  }

  // ...
}
actor.ts

Lifecycle Hooks

See the documentation on the following lifecycle hooks:


Connection List

All active connections can be accessed with this.connections. This is stored as Map<number, Connection> where the key is the connection ID.

This is frequently used with conn.send(name, event) to send messages directly to clients.

For example:

class ChatRoom extends Actor {
  sendDirectMessage(rpc: Rpc<this>, recipient: number, message: string) {
    this.connections.get(recipient, message).send('directMessage', {
      from: rpc.id,
      message: message
    });
  }
}
actor.ts

Disconnecting clients

Connections can be disconnected with:

connection.disconnect();
actor.ts

A reason can optionally be provided like:

connection.disconnect('Too many requests');
actor.ts

Offline & reconnection behavior

Clients automatically attempt to reconnect (with exponential backoff) when disconnected. Remote procedure calls made while disconnected are queued.

On reconnection, event subscriptions are reestablished & queued RPCs are executed.