The Agent class installs the WebSockets capability and calls your onConnect(), onMessage(), onClose(), and onError() methods. Connections hibernate when idle, and useAgent and AgentClient from the client SDK connect to it. This page covers the Agent methods. For connection state, tags, readonly connections, and transports, refer to the WebSockets capability.
import { Agent } from "agents";
export class ChatAgent extends Agent {
getConnectionTags(_connection, ctx) {
const room = new URL(ctx.request.url).searchParams.get("room");
return room ? [`room:${room}`] : [];
}
onConnect(connection, ctx) {
connection.setState({ joinedAt: Date.now() });
connection.send(JSON.stringify({ type: "welcome", id: connection.id }));
}
onMessage(connection, message) {
// Send to everyone except the sender.
this.broadcast(String(message), [connection.id]);
}
onClose(connection) {
this.broadcast(JSON.stringify({ type: "left", id: connection.id }));
}
}import {
Agent,
type Connection,
type ConnectionContext,
type WSMessage,
} from "agents";
export class ChatAgent extends Agent<Env> {
getConnectionTags(_connection: Connection, ctx: ConnectionContext): string[] {
const room = new URL(ctx.request.url).searchParams.get("room");
return room ? [`room:${room}`] : [];
}
onConnect(connection: Connection, ctx: ConnectionContext) {
connection.setState({ joinedAt: Date.now() });
connection.send(JSON.stringify({ type: "welcome", id: connection.id }));
}
onMessage(connection: Connection, message: WSMessage) {
// Send to everyone except the sender.
this.broadcast(String(message), [connection.id]);
}
onClose(connection: Connection) {
this.broadcast(JSON.stringify({ type: "left", id: connection.id }));
}
}Route requests to the Agent with routeAgentRequest(), and check who is calling first. For more information, refer to Authentication.
| Agent method | What it does |
|---|---|
onConnect(connection, ctx) |
Runs after a client connects. ctx.request is the upgrade request |
onMessage(connection, message) |
Runs for each message that is not an Agents protocol frame |
onClose(connection, code, reason, wasClean) |
Runs when a connection closes |
onError(connection, error) |
Runs when a connection fails. The default logs and rethrows |
getConnectionTags(connection, ctx) |
Tags a connection when it is accepted |
broadcast(message, without?) |
Sends to every connection, except the IDs in without |
getConnections(tag?), getConnection(id) |
Finds open connections |
shouldSendProtocolMessages(connection, ctx) |
Return false to turn off identity, state, and MCP frames for a connection |
These methods map to the WebSockets capability's handlers and options. For the Connection object, refer to Connections.
onError() observes errors. If onConnect() or startup throws during an upgrade, the client gets a socket that closes with code 1011, without the error's details. To choose the response instead, override onFetchError().
To reject a client, check it in your Worker with onBeforeConnect, before routeAgentRequest() forwards the upgrade. A client you reject there never reaches the Agent, and the Agent does not wake up for it. Refer to Authentication. You can also reject a connection from onConnect() by calling connection.close(). The Agent runs no message, callable, or state update that the client sends after that close, including frames the client sends as soon as it connects, before it receives the Close frame. onConnect() runs inside the Agent, so every client rejected there still wakes it.
An idle Agent hibernates while its WebSocket connections stay open. A message wakes it, and onMessage() runs as usual. Keep anything you need after a wake in this.state, connection.state, or SQLite, not in class fields. To keep the Agent in memory instead, set static options = { hibernate: false }.