Overview
Agents provide built-in state management with automatic persistence to Durable Object storage and real-time synchronization to all connected WebSocket clients.Setting State
setState()
Update the Agent’s state. Persists to storage and broadcasts to all connected clients.State
required
The new state to set
Error if called from a readonly connection context
How setState() Works
- Validation - Calls
validateStateChange()hook (synchronous) - Persistence - Saves state to Durable Object storage
- Broadcast - Sends state update to all connected clients
- Notification - Calls
onStateChanged()hook (async, non-blocking)
Reading State
state
Access the current state via thestate property.
initialState
Define the initial state for new Agent instances.initialState is only used when the Agent is first created. If state already exists in storage, it takes precedence.State Lifecycle Hooks
validateStateChange()
Called before state is persisted. Throw an error to reject the update. Must be synchronous.State
required
The proposed new state
Connection | 'server'
required
Source of the state update
onStateChanged()
Called after state has been persisted and broadcast. This is a notification hook—errors are routed toonError() and do not affect persistence.
State | undefined
required
The new state
Connection | 'server'
required
Source of the state update
Client-Side State Management
useAgent Hook
React hook for real-time state synchronization.AgentClient
Vanilla JavaScript client for state synchronization.Connection-Level State
Readonly Connections
Mark connections as readonly to prevent state updates.connection.setState()
Connections can have their own isolated state (separate from Agent state).State Persistence
State is automatically persisted to Durable Object SQL storage:State Broadcasting
When state changes, all connected clients receive an update message:Best Practices
Atomic Updates
Always pass the complete state object tosetState():
Validate Before Persist
UsevalidateStateChange() to enforce invariants:
Async Side Effects
UseonStateChanged() for async operations:
State Size
Keep state small (under 128KB recommended). For large data, use SQL or KV:Related
- Agent Class - Agent base class
- useAgent Hook - React state synchronization
- AgentClient - Client-side state management