Agent Request Routing, Instances, and Worker Integration
How Worker Agents use routeAgentRequest and getAgentByName, default URLs, custom paths, auth, email, and webhooks in an existing project.
This page summarises Cloudflare Agents documentation on routing: how HTTP and WebSocket traffic reaches an Agent instance, how to wire that into an existing Worker, and how email and webhooks use the same instance model. An Agent is a class extending the SDK Agent base class; each named instance behaves like an isolated micro-server backed by Durable Objects.
An Agent is a class that extends the base Agent class.
— Cloudflare, Agent class
Each Agent can have millions of instances. Each instance is a separate micro-server that runs independently, allowing horizontal scaling. Instances are addressed by a unique identifier (user ID, email, ticket number, etc.).
— Cloudflare, Agent class
Default routeAgentRequest URL pattern and instance names
Section titled “Default routeAgentRequest URL pattern and instance names”Agent HTTP and WebSocket traffic uses a fixed URL shape unless you customise routing.
Agents are accessed via URL patterns:
https://your-worker.workers.dev/agents/:agent-name/:instance-name— Cloudflare, Agent class
The Routing page breaks the path into class name (kebab-case in the URL) and instance ID (any stable string you choose):
| URL example | Agent class | Instance |
|---|---|---|
/agents/counter/user-123 |
Counter |
user-123 |
/agents/chat-room/lobby |
ChatRoom |
lobby |
/agents/my-agent/default |
MyAgent |
default |
Class names map to kebab-case path segments (MyAgent → /agents/my-agent/...). Clients may pass either casing; the router accepts both.
An instance of an Agent is globally unique: given the same name (or ID), you will always get the same instance of an agent.
— Cloudflare, Agent class
That stability lets you keep per-user or per-entity state on the instance instead of a central session store, and reconnect clients to the same Agent after disconnects.
How routeAgentRequest() chooses an instance
Section titled “How routeAgentRequest() chooses an instance”routeAgentRequest() is the main Worker entry for agent URLs: it parses the path, resolves the Durable Object binding, and returns a Response (including WebSocket upgrades) or undefined if the path is not an agent route.
When a request comes in, routeAgentRequest() examines the URL and routes it to the appropriate agent instance
— Cloudflare, Routing
Under the hood, the Agents layer builds on partyserver name-based Durable Object addressing and re-exports helpers such as getAgentByName and routeAgentRequest (Agent class internals).
Add Agents routing to an existing Worker project
Section titled “Add Agents routing to an existing Worker project”Export the Agent class from the entry point
Section titled “Export the Agent class from the entry point”Durable Object classes must be exported from the Worker’s main module. See Add to existing project.
Your agent class must be exported from your main entry point.
— Cloudflare, Add to existing project
The binding class_name in Wrangler must match the exported class name exactly—mismatches are a common cause of “agent not found” errors (Routing troubleshooting).
Plain Worker fetch handler: try agents first
Section titled “Plain Worker fetch handler: try agents first”Call routeAgentRequest before your other routes so WebSocket upgrades and agent HTTP are not swallowed by a 404 handler.
Use routeAgentRequest() in your Worker to route requests
— Cloudflare, Agent class
Add to existing project shows the pattern: await agent routing, return if matched, then run existing logic.
Hono: agentsMiddleware
Section titled “Hono: agentsMiddleware”For Hono apps, Add to existing project uses hono-agents:
Add agents middleware - handles WebSocket upgrades and agent HTTP requests
— Cloudflare, Add to existing project
Existing routes can stay as they are; middleware runs on * and delegates agent paths to the SDK.
Static assets and route order
Section titled “Static assets and route order”If Wrangler assets serve files from ./public, static files win first; your fetch handler (and routeAgentRequest) only run for non-asset paths.
getAgentByName: server-side RPC without the default URL
Section titled “getAgentByName: server-side RPC without the default URL”Not every call should go through /agents/.... From the same Worker you can obtain a stub and invoke methods directly—useful for REST APIs that fan in to one shared counter or research agent (Add to existing project, Build a Durable AI Agent).
You can interact with agents directly from your Worker code
— Cloudflare, Add to existing project
The Worker routes requests to the Agent, which manages workflow lifecycle. Use routeAgentRequest() for WebSocket connections and getAgentByName() for server-side RPC calls.
— Cloudflare, Build a Durable AI Agent
| Approach | Typical use |
|---|---|
routeAgentRequest(request, env) |
Browser clients, WebSockets, default /agents/{class}/{instance} |
getAgentByName(env.MyAgent, "id") then RPC / agent.fetch(request) |
Internal APIs, custom URL shapes, webhooks after verification |
Optional props passed to getAgentByName (or via routeAgentRequest options) initialise the instance through onStart (Routing).
Custom agent path prefix, basePath, and sub-paths
Section titled “Custom agent path prefix, basePath, and sub-paths”prefix option on routeAgentRequest
Section titled “prefix option on routeAgentRequest”Default paths live under /agents/. You can shift the prefix—for example /api/agents/{agent-name}/{instance-name}—by passing prefix in the third argument (Add to existing project, Quick start).
Client basePath when URLs must not show /agents/
Section titled “Client basePath when URLs must not show /agents/”The client SDK can connect to a clean path such as /user while the server picks the instance (often from session auth) via getAgentByName + agent.fetch(request) (Routing).
The basePath option lets clients connect to any URL path
— Cloudflare, Routing
Recent SDK releases also document basePath for bypassing default URL construction and client onIdentity callbacks when the server sends agent name and type on connect (Agents SDK v0.3.7 changelog).
HTTP sub-paths on an instance
Section titled “HTTP sub-paths on an instance”Paths after the instance segment are delivered to the Agent’s onRequest handler—for example REST under /agents/api/v1/users (Routing, HTTP and Server-Sent Events).
Nested sub-agents and callback URLs
Section titled “Nested sub-agents and callback URLs”For hierarchies (inbox → chat), Sub-agents documents buildAgentPath / buildAgentUrl and routeSubAgentRequest when you parse top-level URLs yourself. The reserved sub segment and URL-encoding rules apply to descendant names.
Authentication before agent routing
Section titled “Authentication before agent routing”You can gate agent traffic in three common ways (Routing, Quick start, Cross-domain authentication):
- Manual — check auth when
pathnamestarts with/agents/(or your custom prefix), then callrouteAgentRequest. - Hooks —
onBeforeConnectandonBeforeRequestonrouteAgentRequestoptions return401/403or allow the request through. - Framework middleware — e.g. Hono
app.use("/agents/*", ...)beforegetAgentByName+agent.fetch.
Cross-origin browser clients should enable CORS on routeAgentRequest (cors: true or custom headers); CORS is delegated to partyserver in recent SDK versions (Agents SDK v0.4.0 changelog). For tokens in WebSocket URLs, follow short TTL, per-agent scoping, validation on every connection, and wss:// in production (Cross-domain authentication).
Email routing: routeAgentEmail and resolvers
Section titled “Email routing: routeAgentEmail and resolvers”Email is a separate Worker entry (email handler) that maps inbound messages to Agent instances (Email, Email agent example).
Prerequisites from the email agent example: domain on Cloudflare Email Service, send_email binding, inbound routing rule to the Worker, optional EMAIL_SECRET for signed reply routing.
Implement onEmail on the Agent; wire the Worker with routeAgentEmail and a resolver:
| Resolver | Purpose |
|---|---|
createAddressBasedEmailResolver("EmailAgent") |
Route by recipient; supports agent+id@domain sub-addresses |
createSecureReplyEmailResolver(env.EMAIL_SECRET) |
Verify HMAC-SHA256 signed headers on replies (secure reply routing) |
createCatchAllEmailResolver(class, instance) |
Single shared inbox instance |
Secure email reply routing — Email replies are now secured with HMAC-SHA256 signed headers, preventing unauthorized routing of emails to agent instances.
— Cloudflare, Agents SDK v0.3.7 changelog
Outbound sendEmail() / replyToEmail() can inject X-Agent-Name and X-Agent-ID and sign them when secret is set (Email agent example). Use isAutoReplyEmail() to avoid loops (Email agent example). Diagnostics for send/receive/reply are listed under Diagnostics channels.
Webhooks: verify at the edge, then getAgentByName
Section titled “Webhooks: verify at the edge, then getAgentByName”Webhooks recommend verifying the provider (signature, raw body) in the Worker before choosing an instance. Derive agentName only from the verified payload—not from an unauthenticated URL segment.
Typical flow:
POSTto/webhooks/{provider}on the Worker.- Verify signature per provider docs.
getAgentByName(env.WebhookAgent, derivedId)andreturn agent.fetch(request).- Inside the Agent,
onRequestparses the event (or usesubmitMessageswith an idempotency key when the provider needs a fast ack—Autonomous responses).
A provider’s body signature does not authenticate the webhook URL. If the URL includes an entity ID, compare it with the corresponding identity from the verified provider payload and reject a mismatch before calling getAgentByName().
— Cloudflare, Webhooks
Client HTTP: agentFetch vs persistent useAgent
Section titled “Client HTTP: agentFetch vs persistent useAgent”For one-off HTTP without a WebSocket, Client SDK documents agentFetch from agents/client:
Use agentFetch |
Use useAgent / AgentClient |
|---|---|
| One-time requests | Real-time updates |
| Server-to-server | Bidirectional RPC / state sync |
| Simple REST-style calls | Multiple calls over one connection |
Common routing mistakes and fixes
Section titled “Common routing mistakes and fixes”Agent not found or HTTP 404
Section titled “Agent not found or HTTP 404”Add to existing project and Routing checklist:
- Export the Agent class from the entry module.
- Wrangler
class_namematches the exported class name. - URL follows
/agents/{agent-name}/{instance-name}(or your custom prefix consistently). - Client
agentname matches the class (case-insensitive). routeAgentRequestis awaited and its response is returned when defined.
WebSocket connection fails
Section titled “WebSocket connection fails”Never wrap the router response; upgrades depend on the original Response object.
Ensure your routing passes the response unchanged:
// Wrong - this breaks WebSocket connections if (agentResponse) return new Response(agentResponse.body);
— Cloudflare, Add to existing project
Enable CORS when the UI origin differs from the Worker (Routing).
basePath connects but server 404s
Section titled “basePath connects but server 404s”The Worker must handle the custom path and forward with getAgentByName + agent.fetch(request); client basePath does not replace server routing (Routing).
How to check this on your site
Section titled “How to check this on your site”-
Confirm each Agent class is exported and listed in Wrangler Durable Object bindings, following Add to existing project and Routing.
-
Deploy or run the Worker locally, then request
https://<your-host>/agents/<kebab-class>/<instance>and expect a response from the Agent (not a generic 404). -
Open a WebSocket to the same path from a browser or client using Client SDK patterns; reject any middleware that rebuilds the
routeAgentRequestresponse. -
For email, send a test message to an address your resolver maps and confirm
onEmailruns per Email agent example. -
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about.