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 { actor } from "actor-core";
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 an actor’s connection state:
Method 1: ConnState
constant
import { actor } from "actor-core";
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: {
// ...
}
});
Method 2: createConnState
function
The data returned from createConnState
is used as the initial state of the connection. The connection state can be accessed through conn.state
.
import { actor } from "actor-core";
const chatRoom = actor({
state: { messages: [] },
// Create connection state dynamically
createConnState: (c) => {
// Validate any connection parameters
// ...
// Return the connection state
return {
userId: generateUserId(),
role: "guest",
joinedAt: Date.now()
};
},
actions: {
sendMessage: (c, message) => {
const username = c.conn.state.userId;
c.state.messages.push({ username, message });
c.broadcast("newMessage", { username, message });
}
}
});
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 "actor-core";
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 "actor-core";
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 Interacting with Actors for details on reconnection behavior.