Files

120 lines
5.1 KiB
Markdown

# Connections
> Source: `src/content/docs/actors/connections.mdx`
> Canonical URL: https://rivet.dev/docs/actors/connections
> Description: Connections represent client connections to your actor. They provide a way to handle client authentication, manage connection-specific data, and control the connection lifecycle.
---
For documentation on connecting to actors from clients, see the [Clients documentation](/docs/clients). For worked presence and chat patterns, see the cookbook: [Live Cursors and Presence](/cookbook/live-cursors/) and [Chat Room](/cookbook/chat-room/).
## Parameters
When clients connect to an actor, they can pass connection parameters that are handled during the connection process. Use `params` for static values, or `getParams` when you need fresh connection data each time a connection opens.
For example:
## Connection State
There are two ways to define an actor's connection state:
### connState
Define connection state as a constant value:
This value will be cloned for every new connection using `structuredClone`.
### createConnState
Create connection state dynamically with a function called for each connection:
## Connection Lifecycle
Each client connection goes through a series of lifecycle hooks that allow you to validate, initialize, and clean up connection-specific resources.
**On Connect** (per client)
- `onBeforeConnect`
- `createConnState`
- `onConnect`
Pending connections are not visible in `c.conns` while `onBeforeConnect` or `createConnState` is running. RivetKit adds the connection to `c.conns` after those hooks succeed and before `onConnect` runs.
**On Disconnect** (per client)
- `onDisconnect`
### `createConnState` and `connState`
[API Reference](/typedoc/interfaces/rivetkit.mod.CreateConnStateContext.html)
There are two ways to define the initial state for connections:
1. `connState`: Define a constant object that will be used as the initial state for all connections
2. `createConnState`: A function that dynamically creates initial connection state based on connection parameters. Can be async.
Connections are not visible in `c.conns` until `createConnState` completes successfully.
### `onBeforeConnect`
[API Reference](/typedoc/interfaces/rivetkit.mod.OnBeforeConnectContext.html)
The `onBeforeConnect` hook is called whenever a new client connects to the actor. Can be async. Clients can pass parameters when connecting, accessible via `params`. This hook is used for connection validation and can throw errors to reject connections.
The `onBeforeConnect` hook does NOT return connection state - it's used solely for validation.
Connections are not visible in `c.conns` while `onBeforeConnect` is running.
Connections cannot interact with the actor until this method completes successfully. Throwing an error will abort the connection. This can be used for authentication, see [Authentication](/docs/actors/authentication) for details.
### `onConnect`
[API Reference](/typedoc/interfaces/rivetkit.mod.OnConnectContext.html)
Executed after the client has successfully connected. Can be async. Receives the connection object as a second parameter.
By the time `onConnect` runs, the connection is visible in `c.conns`.
Messages will not be processed for this actor until this hook succeeds. Errors thrown from this hook will cause the client to disconnect.
### `onDisconnect`
[API Reference](/typedoc/interfaces/rivetkit.mod.ActorDefinition.html)
Called when a client disconnects from the actor. Can be async. Receives the connection object as a second parameter. Use this to clean up any connection-specific resources.
## Connection List
All active connections can be accessed through the context object's `conns` property. This is a `Map<string, Conn>` of all current connections, keyed by connection ID.
This is frequently used with `conn.send(name, event)` to send messages directly to clients. To send an event to all connections at once, use `c.broadcast()` instead. See [Events](/docs/actors/events) for more details on broadcasting.
For example:
`conn.send()` has no effect on [low-level WebSocket connections](/docs/actors/websocket-handler). For low-level WebSockets, use the WebSocket API directly (e.g., `websocket.send()`).
## Disconnecting clients
Connections can be disconnected from within an action:
If you need to wait for the disconnection to complete, you can use `await`:
This ensures the underlying network connections close cleanly before continuing.
## API Reference
- [`Conn`](/typedoc/interfaces/rivetkit.mod.Conn.html) - Connection interface
- [`ConnInitContext`](/typedoc/interfaces/rivetkit.mod.ConnInitContext.html) - Connection initialization context
- [`CreateConnStateContext`](/typedoc/interfaces/rivetkit.mod.CreateConnStateContext.html) - Context for creating connection state
- [`OnBeforeConnectContext`](/typedoc/interfaces/rivetkit.mod.OnBeforeConnectContext.html) - Pre-connection lifecycle hook context
- [`OnConnectContext`](/typedoc/interfaces/rivetkit.mod.OnConnectContext.html) - Post-connection lifecycle hook context
- [`ActorConn`](/typedoc/types/rivetkit.client_mod.ActorConn.html) - Typed connection from client side
_Source doc path: /docs/actors/connections_