Skip to main content

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
required
The incoming HTTP request
Env
required
Environment containing Agent bindings
AgentOptions<Env>
Routing options
string
default:"agents"
URL prefix for agent routing (e.g., “/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>
Returns: Promise<Response | undefined> - Response from the Agent, or undefined if no route matched

Custom Prefix

Custom Agent Mapping

getAgentByName()

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

Basic Usage

With Jurisdiction

With Props

Returns: Promise<DurableObjectStub<T>> - Agent instance stub

Custom Routing

For advanced use cases, implement custom routing logic:

Session-Based Routing

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.
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.