Lifecycle
Understand actor lifecycle hooks and initialization patterns
Actors follow a well-defined lifecycle with hooks at each stage. Understanding these hooks is essential for proper initialization, state management, and cleanup.
Lifecycle Hooks
Actor lifecycle hooks are defined as functions in the actor configuration.
createState
and state
The createState
function or state
constant defines the initial state of the actor (see state documentation). The createState
function is called only once when the actor is first created.
createVars
and vars
The createVars
function or vars
constant defines ephemeral variables for the actor (see state documentation). These variables are not persisted and are useful for storing runtime-only objects or temporary data.
The createVars
function can also receive driver-specific context as its second parameter, allowing access to driver capabilities like Rivet KV or Cloudflare Durable Object storage.
onCreate
The onCreate
hook is called at the same time as createState
, but unlike createState
, it doesn't return any value. Use this hook for initialization logic that doesn't affect the initial state.
onStart
This hook is called any time the actor is started (e.g. after restarting, upgrading code, or crashing).
This is called after the actor has been initialized but before any connections are accepted.
Use this hook to set up any resources or start any background tasks, such as setInterval
.
onStateChange
Called whenever the actor's state changes. This is often used to broadcast state updates.
createConnState
and connState
There are two ways to define the initial state for connections:
connState
: Define a constant object that will be used as the initial state for all connectionscreateConnState
: A function that dynamically creates initial connection state based on connection parameters
onBeforeConnect
The onBeforeConnect
hook is called whenever a new client connects to the actor. 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 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 for details.
onConnect
Executed after the client has successfully connected.
Messages will not be processed for this actor until this hook succeeds. Errors thrown from this hook will cause the client to disconnect.
onDisconnect
Called when a client disconnects from the actor. Use this to clean up any connection-specific resources.
onFetch
The onFetch
hook handles HTTP requests sent to your actor. It receives the actor context and a standard Request
object, and should return a Response
object or void
to continue default routing.
onWebSocket
The onWebSocket
hook handles WebSocket connections to your actor. It receives the actor context, a WebSocket
object, and the initial Request
. Use this to set up WebSocket event listeners and handle real-time communication.
onAuth
The onAuth
hook is called on the HTTP server before clients can interact with the actor. This hook is required for any public HTTP endpoint access and is used to validate client credentials and return authentication data that will be available on connections.
This hook runs on the HTTP server (not the actor) to reduce load and prevent denial of service attacks against individual actors. Only called for public endpoints - calls to actors from within the backend do not trigger this handler.
onBeforeActionResponse
The onBeforeActionResponse
hook is called before sending an action response to the client. Use this hook to modify or transform the output of an action before it's sent to the client. This is useful for formatting responses, adding metadata, or applying transformations to the output.
Destroying Actors
Destroying actors is not available yet.
Advanced
Running Background Tasks
The c.runInBackground
method allows you to execute promises asynchronously without blocking the actor's main execution flow. The actor is prevented from sleeping while the promise passed to runInBackground
is still active. This is useful for fire-and-forget operations where you don't need to wait for completion.
Common use cases:
- Analytics and logging: Send events to external services without delaying responses
- State sync: Populate external databases or APIs with updates to actor state in the background
Using ActorContext
Type Externally
When extracting logic from lifecycle hooks or actions into external functions, you'll often need to define the type of the context parameter. Rivet provides helper types that make it easy to extract and pass these context types to external functions.
See Helper Types for more details on using ActorContextOf
.