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 a actor, they can pass connection parameters that are handled during the connection process.

For example:

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

const gameRoom = actor({
  state: {},
  
  // Handle connection setup
  createConnState: (c, { params }) => {
    // Validate authentication token
    const authToken = params.authToken;
    
    if (!authToken || !validateToken(authToken)) {
      throw new Error("Invalid auth token");
    }
    
    // Create connection state
    return { userId: getUserIdFromToken(authToken), role: "player" };
  },
  
  actions: {
    // ...
  }
});

Connection State

There are two ways to define a actor’s connection state:

Define connection state as a constant value:

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: {
    // ...
  }
});

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:

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:

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:

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

This ensures the underlying network connections close cleanly before continuing.

Offline & Auto-Reconnection

See client documentation for details on reconnection behavior.