Sign In
Communication

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:

import { createClient } from "rivetkit/client";
import type { registry } from "./src/index";

const client = createClient<typeof registry>("http://localhost:8080");
const gameRoom = await client.gameRoom.get({
  params: { authToken: "supersekure" }
});

Connection State

There are two ways to define an actor's connection state:

Define connection state as a constant value:

TypeScript
import { actor } from "@rivetkit/actor";

const chatRoom = actor({
  state: { messages: [] },
  
  // Define default connection state as a constant
  connState: {
    role: "guest",
    joinedAt: 0
  },
  
  onConnect: (c) => {
    // Update join timestamp when a client connects
    c.conn.state.joinedAt = Date.now();
  },
  
  actions: {
    // ...
  }
});

This value will be cloned for every new connection using structuredClone.

Connection Lifecycle Hooks

The connection lifecycle has several hooks:

  • onBeforeConnect: Called before a client connects, returns the connection state
  • onConnect: Called when a client successfully connects
  • onDisconnect: Called when a client disconnects

See the documentation on Actor Lifecycle for more details.

Connection List

All active connections can be accessed through the context object's conns property. This is an array of all current connections.

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

For example:

TypeScript
import { actor } from "@rivetkit/actor";

const chatRoom = actor({
  state: { users: {} },
  
  actions: {
    sendDirectMessage: (c, recipientId, message) => {
      // Find the recipient's connection
      const recipientConn = c.conns.find(conn => conn.state.userId === recipientId);
      
      if (recipientConn) {
        // Send a private message to just that client
        recipientConn.send('directMessage', {
          from: c.conn.state.userId,
          message: message
        });
      }
    }
  }
});

Disconnecting clients

Connections can be disconnected from within an action:

TypeScript
import { actor } from "@rivetkit/actor";

const secureRoom = actor({
  state: {},
  
  actions: {
    kickUser: (c, targetUserId, reason) => {
      // Find the connection to kick
      const targetConn = c.conns.find(conn => conn.state.userId === targetUserId);
      
      if (targetConn) {
        // Disconnect with a reason
        targetConn.disconnect(reason || "Kicked by admin");
      }
    }
  }
});

If you need to wait for the disconnection to complete, you can use await:

TypeScript
await c.conn.disconnect('Too many requests');

This ensures the underlying network connections close cleanly before continuing.

Connection Error Handling

Handle connection errors using the .onError() method:

const connection = actor.connect();

connection.onError((error) => {
  console.error('Connection error:', error);
  showErrorMessage(error.message);
  
  // Handle specific error types
  if (error.code === 'UNAUTHORIZED') {
    redirectToLogin();
  } else if (error.code === 'ACTOR_NOT_FOUND') {
    showActorNotFoundError();
  }
});

Offline & Auto-Reconnection

See client documentation for details on reconnection behavior.

Suggest changes to this page