Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/cloudflare/agents/llms.txt

Use this file to discover all available pages before exploring further.

Overview

Cloudflare Agents provides utilities for routing HTTP requests and emails to the appropriate Agent instances based on URL patterns, email addresses, or custom logic.

routeAgentRequest()

Route an HTTP request to the appropriate Agent based on URL pattern.
request
Request
required
The incoming HTTP request
env
Env
required
Environment containing Agent bindings
options
AgentOptions<Env>
Routing options
agentsPrefix
string
default:"agents"
URL prefix for agent routing (e.g., “/agents”)
agents
Record<string, DurableObjectNamespace>
Custom mapping of agent names to namespaces. If not provided, all Durable Object bindings in env are used.

Standard Routing

By default, routes follow the pattern: /<prefix>/<agent-class>/<agent-name>
export default {
  async fetch(request: Request, env: Env) {
    // Routes:
    // /agents/my-agent/room-123 → MyAgent instance "room-123"
    // /agents/chat-agent/user-456 → ChatAgent instance "user-456"
    const response = await routeAgentRequest(request, env);
    if (response) return response;

    return new Response("Not found", { status: 404 });
  }
};
Returns: Promise<Response | undefined> - Response from the Agent, or undefined if no route matched

Custom Prefix

await routeAgentRequest(request, env, {
  agentsPrefix: "api/agents"
});
// Now routes: /api/agents/my-agent/room-123

Custom Agent Mapping

await routeAgentRequest(request, env, {
  agents: {
    chat: env.CHAT_AGENT,
    support: env.SUPPORT_AGENT
  }
});
// Routes:
// /agents/chat/room-123 → CHAT_AGENT instance "room-123"
// /agents/support/ticket-456 → SUPPORT_AGENT instance "ticket-456"

getAgentByName()

Get or create an Agent instance by name.
namespace
DurableObjectNamespace<T>
required
Agent namespace from environment bindings
name
string
required
Name of the Agent instance
options
GetAgentByNameOptions
jurisdiction
DurableObjectJurisdiction
Durable Object jurisdiction (e.g., “eu”)
locationHint
DurableObjectLocationHint
Location hint for Durable Object placement
props
Props
Props to pass to the Agent’s onStart() method

Basic Usage

const agent = await getAgentByName(env.MY_AGENT, "room-123");
const response = await agent.fetch(request);

With Jurisdiction

const agent = await getAgentByName(
  env.MY_AGENT,
  "eu-user-456",
  { jurisdiction: "eu" }
);

With Props

const agent = await getAgentByName(
  env.MY_AGENT,
  "session-789",
  { props: { userId: "user-123", tier: "premium" } }
);
Returns: Promise<DurableObjectStub<T>> - Agent instance stub

Custom Routing

For advanced use cases, implement custom routing logic:
export default {
  async fetch(request: Request, env: Env) {
    const url = new URL(request.url);

    // Extract user ID from auth token
    const userId = await getUserIdFromAuth(request);

    // Route based on auth context, not URL
    const agent = await getAgentByName(env.USER_AGENT, userId);
    return agent.fetch(request);
  }
};

Session-Based Routing

export default {
  async fetch(request: Request, env: Env) {
    const sessionId = request.headers.get("X-Session-ID");
    if (!sessionId) {
      return new Response("Missing session", { status: 401 });
    }

    const agent = await getAgentByName(env.SESSION_AGENT, sessionId);
    return agent.fetch(request);
  }
};

Email Routing

See the Email API reference for email-specific routing utilities:
  • routeAgentEmail() - Route emails to Agents
  • createAddressBasedEmailResolver() - Route by email address
  • createSecureReplyEmailResolver() - Route secure reply emails
  • createCatchAllEmailResolver() - Route all emails to one Agent

getCurrentAgent()

Get the current Agent from within a callable method or lifecycle hook.
import { getCurrentAgent } from "agents";

function helperFunction() {
  const { agent, connection, request, email } = getCurrentAgent<MyAgent>();

  if (agent) {
    // Access agent.state, agent.sql(), etc.
  }
}
Returns: Object with:
  • agent - Current Agent instance (or undefined)
  • connection - Current WebSocket connection (or undefined)
  • request - Current HTTP request (or undefined)
  • email - Current email (or undefined)
getCurrentAgent() only works when called from within Agent methods, callable functions, or lifecycle hooks. It returns undefined when called outside the Agent context.

Build docs developers (and LLMs) love