Routing
This guide explains how requests are routed to agents, how naming works, and patterns for organizing your agents.
When a request comes in, routeAgentRequest() examines the URL and routes it to the appropriate agent instance:
https://your-worker.dev/agents/{agent-name}/{instance-name} └────┬────┘ └─────┬─────┘ Class name Unique instance ID (kebab-case)Example URLs:
| URL | Agent Class | Instance |
|---|---|---|
/agents/counter/user-123 | Counter | user-123 |
/agents/chat-room/lobby | ChatRoom | lobby |
/agents/my-agent/default | MyAgent | default |
Agent class names are automatically converted to kebab-case for URLs:
| Class Name | URL Path |
|---|---|
Counter | /agents/counter/... |
MyAgent | /agents/my-agent/... |
ChatRoom | /agents/chat-room/... |
AIAssistant | /agents/ai-assistant/... |
The router matches both the original name and kebab-case version, so you can use either:
useAgent({ agent: "Counter" })→/agents/counter/...useAgent({ agent: "counter" })→/agents/counter/...
The routeAgentRequest() function is the main entry point for agent routing:
import { routeAgentRequest } from "agents";
export default { async fetch(request, env, ctx) { // Route to agents - returns Response or undefined const agentResponse = await routeAgentRequest(request, env);
if (agentResponse) { return agentResponse; }
// No agent matched - handle other routes return new Response("Not found", { status: 404 }); },};import { routeAgentRequest } from "agents";
export default { async fetch(request: Request, env: Env, ctx: ExecutionContext) { // Route to agents - returns Response or undefined const agentResponse = await routeAgentRequest(request, env);
if (agentResponse) { return agentResponse; }
// No agent matched - handle other routes return new Response("Not found", { status: 404 }); },} satisfies ExportedHandler<Env>;The instance name (the last part of the URL) determines which agent instance handles the request. Each unique name gets its own isolated agent with its own state.
Each user gets their own agent instance:
// Clientconst agent = useAgent({ agent: "UserProfile", name: `user-${userId}`, // e.g., "user-abc123"});// Clientconst agent = useAgent({ agent: "UserProfile", name: `user-${userId}`, // e.g., "user-abc123"});/agents/user-profile/user-abc123 → User abc123's agent/agents/user-profile/user-xyz789 → User xyz789's agent (separate instance)Multiple users share the same agent instance:
// Clientconst agent = useAgent({ agent: "ChatRoom", name: roomId, // e.g., "general" or "room-42"});