All Agent Engineering

Cloudflare Agent WebSockets: read connection state after hibernation

Store a joining timestamp in connection.state, read it on messages and distinguish ordinary checks from observed wake-up checks.

AINavWritten / Updated
On this page

At a glance

An idle Cloudflare Agent can hibernate while WebSockets remain open. A new message wakes it and runs onMessage. Data needed afterward belongs in this.state, connection.state or SQLite. This task stores a joining timestamp per connection and reads it through a message, delivering code and a wake-up acceptance record. Two messages alone do not prove hibernation occurred between them. No Worker, WebSocket or deployment was run.

Runtime and applicability

Article type
Engineering practice
Verified
Applies to
  • Cloudflare Agents SDK Agent connection information and hibernation boundaries

Execution locations and responsibilities

  • Worker Agent class behind authenticated routing Save connection data, validate messages and read connection state.
  • WebSocket client and runtime observation environment Check frames, closure and observed wake-up, marking missing evidence unconfirmed.

When to use

  • An Agent with authenticated routing needs connection information that remains readable after hibernation.

When not to use

  • Class fields are not persistent wake-up state. This example does not restore an earlier session after reconnection.
  • URL tags, connection IDs and joining times are not identity authentication or instance authorization.

Use an existing authenticated entry point

An existing SDK project must provide an Agent class, a client connection and routeAgentRequest after caller checks. Replace only an owned demonstration class; this task supplies no unverified deployment setup. Authentication and instance authorization have their own article. The synthetic message is {"type":"joined_at"}, with no real account or business data.

Store the timestamp on the connection

onConnect runs after a client connects. The example saves joinedAt with connection.setState and sends welcome. onMessage handles non-Agents protocol frames and accepts only the specified text JSON. Invalid input sends an error and stops that frame. The teaching contract creates no timers, network tools or background work; the timestamp checks state ownership.

Example: connection state readback in an existing project
javascript
import { Agent } from "agents";

export class ConnectionAgent extends Agent {
  onConnect(connection) {
    connection.setState({ joinedAt: Date.now() });
    connection.send(JSON.stringify({ type: "welcome", id: connection.id }));
  }

  onMessage(connection, message) {
    let request;
    try {
      if (typeof message !== "string") throw new Error("Text frame required");
      request = JSON.parse(message);
      if (request?.type !== "joined_at") throw new Error("Unknown message");
    } catch {
      connection.send(JSON.stringify({ type: "error", code: "invalid_message" }));
      return;
    }
    const joinedAt = connection.state?.joinedAt;
    if (!Number.isFinite(joinedAt)) {
      connection.send(JSON.stringify({ type: "error", code: "missing_state" }));
      return;
    }
    connection.send(JSON.stringify({ type: "joined_at", joinedAt }));
  }

  onClose(connection) {
    console.log("connection closed", connection.id);
  }
}

Read connection state when a message wakes the Agent

onMessage reads connection.state instead of a constructor value or class field. The documented idle Agent keeps connections open while hibernating, and onMessage runs normally after a wake. hibernate: false can keep it in memory; this example retains default hibernation. joinedAt belongs only to the current connection. A new connection runs onConnect again, so its timestamp does not prove old-session recovery.

Lifecycle flow
EventState locationAcceptance
Connectconnection.setStateWelcome identifies the current connection
Ordinary messageconnection.statejoined_at returns its original timestamp
Message after idle wakeConnection state againActual hibernation observation is required
Close or new connectiononClose / new onConnectKeep closure record; new joining time belongs to new connection

Check state, protocol and observation evidence

In your demonstration environment, connect, retain welcome and send joined_at. Repeated messages should return the same joining time; that is an ordinary state check. A cross-hibernation claim also requires actual runtime observation of hibernation and wake-up on the same open connection. The page does not define an observation API or waiting interval. Do not assume a few seconds guarantees hibernation. Mark this part unconfirmed if no evidence is available, retaining ordinary message checks.

Give failures and closure explicit exits

  • Nontext frames, invalid JSON and unknown types send invalid_message and stop that frame.
  • Missing state sends missing_state; do not replace the earlier timestamp with Date.now.
  • onClose retains diagnostics; clients stop using the old connection. Reconnection creates a new one.
  • Keep actual runtime errors rather than accept a normal result. Default onError logs and rethrows; no custom error strategy is implemented.
  • An observation timeout records missing hibernation evidence and ends acceptance waiting without a passing wake-up claim.

Verification and storage scope

The current Agent class WebSockets page was read fully for callbacks, hibernation and state locations. This code only routes input and reads state. No Worker or browser was run; costs, SDK compatibility and reconnection were not tested. this.state stores Agent state, connection.state connection information and SQLite separate persistent records. Only connection state is used, without inferring an account-storage design.

Sources

All links are official pages; verification dates are listed per source, and links point to the version checked.

  1. Cloudflare · WebSockets — Agent class

Found an error? Tell us →