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

# Routing

> Route HTTP requests and emails to Agents

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

<ParamField path="request" type="Request" required>
  The incoming HTTP request
</ParamField>

<ParamField path="env" type="Env" required>
  Environment containing Agent bindings
</ParamField>

<ParamField path="options" type="AgentOptions<Env>">
  Routing options

  <ParamField path="agentsPrefix" type="string" default="agents">
    URL prefix for agent routing (e.g., "/agents")
  </ParamField>

  <ParamField path="agents" type="Record<string, DurableObjectNamespace>">
    Custom mapping of agent names to namespaces. If not provided, all Durable Object bindings in env are used.
  </ParamField>
</ParamField>

### Standard Routing

By default, routes follow the pattern: `/<prefix>/<agent-class>/<agent-name>`

```typescript theme={null}
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

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

### Custom Agent Mapping

```typescript theme={null}
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.

<ParamField path="namespace" type="DurableObjectNamespace<T>" required>
  Agent namespace from environment bindings
</ParamField>

<ParamField path="name" type="string" required>
  Name of the Agent instance
</ParamField>

<ParamField path="options" type="GetAgentByNameOptions">
  <ParamField path="jurisdiction" type="DurableObjectJurisdiction">
    Durable Object jurisdiction (e.g., "eu")
  </ParamField>

  <ParamField path="locationHint" type="DurableObjectLocationHint">
    Location hint for Durable Object placement
  </ParamField>

  <ParamField path="props" type="Props">
    Props to pass to the Agent's onStart() method
  </ParamField>
</ParamField>

### Basic Usage

```typescript theme={null}
const agent = await getAgentByName(env.MY_AGENT, "room-123");
const response = await agent.fetch(request);
```

### With Jurisdiction

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

### With Props

```typescript theme={null}
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:

```typescript theme={null}
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

```typescript theme={null}
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](/api/email) 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.

```typescript theme={null}
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)

<Note>
  `getCurrentAgent()` only works when called from within Agent methods, callable functions, or lifecycle hooks. It returns undefined when called outside the Agent context.
</Note>

## Related

* [Agent Class](/api/agent-class) - Agent base class
* [Email Routing](/api/email) - Email-specific routing
