Cloudflare Agent SQL: store records outside broadcast state
Read and write a teaching record in per-Agent SQLite, with interpolated parameters and a clear SQL-versus-state boundary.
Place it in an existing Agent project · 1. Create the table when the instance starts · 2. Write and query with interpolated parameters
At a glance
A Cloudflare Agent instance has an embedded SQLite database accessed through this.sql. Data kept internally without client synchronization can be organized in SQL. This task creates a teaching note table, writes a record by ID and reads it back. Its deliverable is a server-side storage interface and checks. SQL placement alone does not establish access control.
Runtime and applicability
- Article type
- Engineering practice
- Verified
- Applies to
- Cloudflare Agents SDK Use the cited documentation and version scope. Not tested.
Execution locations and responsibilities
- The Worker Agent class, onStart and existing server-side caller Initialize the instance table and read or write by stable ID while retaining entry-point authorization.
Arrows show the order of checks in the guide. Follow each step’s prerequisites, branches and stop conditions; unexecuted steps are not completed work.
When to use
- An existing Agent needs small structured records outside client-synchronized state.
When not to use
- Use the State API for client synchronization and resolve unknown migrations or access permissions first.
Place it in an existing Agent project
The example belongs in a Worker project that already supports the Agent base class and Durable Object binding. Export and bind Notes using the project’s existing conventions. Before changing an existing Agent, inspect its class, migrations and other methods so that they remain intact. This article does not provide deployment from scratch or create cloud resources. Call these methods through an existing authorized server-side path.
1. Create the table when the instance starts
The documented onStart runs on startup or wake from hibernation. CREATE TABLE IF NOT EXISTS preserves an existing table and its records; it does not migrate an incompatible schema. The notes table, id and body are teaching fields. If an existing deployment has a different table with that name, decide its migration first rather than claiming IF NOT EXISTS completes the upgrade.
2. Write and query with interpolated parameters
import { Agent } from "agents";
type Note = { id: string; body: string };
export class Notes extends Agent {
onStart() {
this.sql`CREATE TABLE IF NOT EXISTS notes (
id TEXT PRIMARY KEY,
body TEXT NOT NULL
)`;
}
saveNote(id: string, body: string) {
this.sql`INSERT OR REPLACE INTO notes (id, body) VALUES (${id}, ${body})`;
}
readNote(id: string): Note[] {
return this.sql<Note>`SELECT id, body FROM notes WHERE id = ${id}`;
}
}
this.sql is a tagged-template API. Put values in ${id} and ${body} rather than constructing SQL through string concatenation. The example chooses SQLite INSERT OR REPLACE, so a repeated ID replaces its record rather than preserving versions. Versioned notes need a different schema and key design. The query explicitly selects id and body; the Note type describes returned fields to callers.
3. Verify the same ID on readback
| Action | Check |
|---|---|
Save ID sample and body paper cup | Call saveNote through the existing server path and record success or failure |
Read ID sample | Returned id and body match the input |
| Save a new body under the same ID | Check replacement under this example’s rule |
| Read an absent ID | Handle the actual no-row result without inventing a note |
The table is a checklist, not a fabricated cloud execution. Keep the actual readback result; reading after the instance wakes can check persistence in the current environment. The code defines server-side methods and adds no browser @callable method or HTTP entry.
SQL and state serve different purposes
The reference provides SQL for the instance database and the State API for client-synchronized values. SQL avoids using state synchronization for the note, but a public method, route, log or other code can still expose it. Storage location is not a complete confidentiality guarantee. Verify identity and authorization at the actual entry point, and put only intended client data into synchronized state.
Completion and verification scope
- The schema fits migration history and replacement by ID fits the task.
- Server-side calls read back actual data using tagged-template values.
- Internal notes stay out of broadcast state and existing routes and logs do not widen access.
The official Agent class reference was read to check onStart, SQL templates and the State API distinction. No SDK was installed, Worker deployed or actual Agent database accessed. The TypeScript class illustrates documented interfaces. Integration must retain existing permission, binding and migration rules.
Sources
All links are official pages; verification dates are listed per source, and links point to the version checked.