Deploy to any runtime
Deploy the CopilotKit runtime on any backend framework: Node.js, Express, Hono, Bun, Deno, Cloudflare Workers, and more.
Your agent needs a backend endpoint, and you already run a server. Pick your server below and copy its handler. The TypeScript CopilotKit runtime is a Fetch handler: a function that takes a Request and returns a Response. It runs on any platform that supports the Fetch API. For Node.js HTTP servers, Express, and Hono, CopilotKit ships thin adapters.
TypeScript server adapters
This guide covers the TypeScript runtime, which works with or without Intelligence. For Python, Go, Ruby, or C#/.NET servers, follow the Intelligence quickstart. Those runtimes require Intelligence and expose multi-route endpoints.
Quick Overview
| Runtime | Import Path | Key Function |
|---|---|---|
| Fetch-native (Bun, Deno, CF Workers, Next.js App Router) | @copilotkit/runtime/v2 | createCopilotRuntimeHandler |
| Node.js HTTP | @copilotkit/runtime/v2/node | createCopilotNodeHandler / createCopilotNodeListener |
| Express | @copilotkit/runtime/v2/express | createCopilotExpressHandler |
| Hono | @copilotkit/runtime/v2/hono | createCopilotHonoHandler |
Multi-Route vs Single-Route
The runtime supports two endpoint modes:
-
Multi-route (default) exposes individual URL endpoints:
GET {basePath}/infoPOST {basePath}/agent/:agentId/runPOST {basePath}/agent/:agentId/connectPOST {basePath}/agent/:agentId/stop/:threadIdPOST {basePath}/transcribe
-
Single-route exposes a single
POST {basePath}endpoint that accepts a JSON envelope:{ "method": "agent/run", "params": { "agentId": "default" }, "body": { ... } }
Both modes use the same Runtime handlers. Single-route mode also carries Intelligence thread, memory, and annotation operations.
Single-route mode is useful when your platform only allows one route handler, or when you prefer a simpler URL structure.
Fetch-Native Runtimes
If your platform supports the Fetch API natively (Bun, Deno, Cloudflare Workers, etc.), you can use createCopilotRuntimeHandler directly. No adapter is needed.
import { CopilotRuntime, createCopilotRuntimeHandler, BuiltInAgent } from "@copilotkit/runtime/v2";
// 1. Create the runtime with your agent(s)
const runtime = new CopilotRuntime({
agents: {
default: new BuiltInAgent({ model: "openai/gpt-6-luna" }),
},
});
// 2. Create a Fetch handler — takes Request, returns Response
const handler = createCopilotRuntimeHandler({
runtime,
basePath: "/api/copilotkit",
cors: true,
});
// 3. Serve it (Bun example — works the same with Deno.serve, CF Workers, etc.)
Bun.serve({ fetch: handler, port: 4000 });For framework-specific examples, see the sections below.
Bun
import { CopilotRuntime, createCopilotRuntimeHandler, BuiltInAgent } from "@copilotkit/runtime/v2";
// Configure the runtime with your agent(s)
const runtime = new CopilotRuntime({
agents: {
default: new BuiltInAgent({ model: "openai/gpt-6-luna" }),
},
});
// Create a Fetch handler with multi-route endpoints (GET /info, POST /agent/:id/run, etc.)
const handler = createCopilotRuntimeHandler({
runtime,
basePath: "/api/copilotkit",
cors: true,
});
// Bun natively supports Fetch handlers
Bun.serve({ fetch: handler, port: 4000 });Deno
import { CopilotRuntime, createCopilotRuntimeHandler, BuiltInAgent } from "@copilotkit/runtime/v2";
const runtime = new CopilotRuntime({
agents: {
default: new BuiltInAgent({ model: "openai/gpt-6-luna" }),
},
});
const handler = createCopilotRuntimeHandler({
runtime,
basePath: "/api/copilotkit",
cors: true,
});
// Deno.serve natively accepts a Fetch handler
Deno.serve({ port: 4000 }, handler);Cloudflare Workers
Do not construct an agent at module scope
Workers do not allow random values in global scope, and an agent generates a
thread ID when you construct it. An agent created at the top level of the module
stops the Worker from starting, with Disallowed operation called within global scope. The examples below construct everything inside fetch. To create the
runtime once at module scope, pass agents as a factory. The runtime calls the
factory on each request:
const runtime = new CopilotRuntime({
agents: () => ({
default: new BuiltInAgent({ model: "openai/gpt-6-luna" }),
}),
});import { CopilotRuntime, createCopilotRuntimeHandler, BuiltInAgent } from "@copilotkit/runtime/v2";
export interface Env {
OPENAI_API_KEY: string;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const runtime = new CopilotRuntime({
agents: {
default: new BuiltInAgent({ model: "openai/gpt-6-luna" }),
},
});
// Workers use the Fetch API natively — handler plugs in directly
const handler = createCopilotRuntimeHandler({
runtime,
basePath: "/api/copilotkit",
cors: true,
});
return handler(request);
},
};Next.js App Router
import { CopilotRuntime, createCopilotRuntimeHandler, BuiltInAgent } from "@copilotkit/runtime/v2";
const runtime = new CopilotRuntime({
agents: {
default: new BuiltInAgent({ model: "openai/gpt-6-luna" }),
},
});
const handler = createCopilotRuntimeHandler({
runtime,
basePath: "/api/copilotkit",
});
// Export every method used by the multi-route Runtime.
export { handler as GET, handler as POST, handler as PATCH, handler as DELETE };No cors: true needed for Next.js. Same-origin requests don't require CORS headers.
React Router (Framework Mode)
React Router v7 in framework mode uses file-based routing with Fetch API handlers. The CopilotKit handler works directly as a resource route.
import { CopilotRuntime, createCopilotRuntimeHandler, BuiltInAgent } from "@copilotkit/runtime/v2";
import type { Route } from "./+types/api.copilotkit.$";
const runtime = new CopilotRuntime({
agents: {
default: new BuiltInAgent({ model: "openai/gpt-6-luna" }),
},
});
const handler = createCopilotRuntimeHandler({
runtime,
basePath: "/api/copilotkit",
});
// loader handles GET requests (e.g. /info)
export function loader({ request }: Route.LoaderArgs) {
return handler(request);
}
// action handles POST requests (e.g. /agent/:id/run)
export function action({ request }: Route.ActionArgs) {
return handler(request);
}The $ splat segment in the filename (api.copilotkit.$.ts) captures all subpaths under /api/copilotkit/. The CopilotKit router then handles /info and /agent/:id/run.
TanStack Start
TanStack Start uses API routes that receive standard Request objects and return Response objects.
import { createAPIFileRoute } from "@tanstack/react-start/api";
import { CopilotRuntime, createCopilotRuntimeHandler, BuiltInAgent } from "@copilotkit/runtime/v2";
const runtime = new CopilotRuntime({
agents: {
default: new BuiltInAgent({ model: "openai/gpt-6-luna" }),
},
});
const handler = createCopilotRuntimeHandler({
runtime,
basePath: "/api/copilotkit",
});
// The $ splat matches all subpaths and forwards every Runtime method.
export const APIRoute = createAPIFileRoute("/api/copilotkit/$")({
GET: ({ request }) => handler(request),
POST: ({ request }) => handler(request),
PATCH: ({ request }) => handler(request),
DELETE: ({ request }) => handler(request),
});The $ in the filename is TanStack Start's splat parameter, matching all subpaths under /api/copilotkit/.
Node.js HTTP
For vanilla Node.js HTTP servers, use the /node subpath which bridges Fetch to Node's IncomingMessage/ServerResponse.
import { createServer } from "node:http";
import { CopilotRuntime, BuiltInAgent } from "@copilotkit/runtime/v2";
import { createCopilotNodeListener } from "@copilotkit/runtime/v2/node";
const runtime = new CopilotRuntime({
agents: {
default: new BuiltInAgent({ model: "openai/gpt-6-luna" }),
},
});
// createCopilotNodeListener returns a Node request listener (req, res) => void
// that bridges to the Fetch handler internally
const listener = createCopilotNodeListener({
runtime,
basePath: "/api/copilotkit",
cors: true,
});
createServer(listener).listen(4000, () => {
console.log("Listening at http://localhost:4000/api/copilotkit");
});Express
The Express adapter returns an Express router. Mount it with app.use(). It
works with Express 4 and Express 5.
express is an optional peer dependency of @copilotkit/runtime, so install it
in your own app. Both majors are supported.
npm install express corsimport express from "express";
import { CopilotRuntime, BuiltInAgent } from "@copilotkit/runtime/v2";
import { createCopilotExpressHandler } from "@copilotkit/runtime/v2/express";
const runtime = new CopilotRuntime({
agents: {
default: new BuiltInAgent({ model: "openai/gpt-6-luna" }),
},
});
const app = express();
// Mount the CopilotKit router — creates Express routes under /api/copilotkit
app.use(
createCopilotExpressHandler({
runtime,
basePath: "/api/copilotkit",
cors: true,
}),
);
app.listen(4000, () => {
console.log("Listening at http://localhost:4000/api/copilotkit");
});Express Options
| Option | Type | Default | Description |
|---|---|---|---|
runtime | CopilotRuntime | required | The runtime instance |
basePath | string | required | URL path prefix (e.g. "/api/copilotkit") |
mode | "multi-route" | "single-route" | "multi-route" | Multi-route exposes individual endpoints; single-route uses a JSON envelope |
cors | boolean | CorsOptions | true | CORS configuration. Defaults to permissive (origin: "*"). Pass false to handle CORS yourself, or pass a cors options object |
hooks | CopilotRuntimeHooks | none | Lifecycle hooks |
The Express adapter is compatible with express.json() body parsing. If you have app.use(express.json()) before the CopilotKit router, the adapter will detect the pre-parsed body and handle it correctly.
Hono
The Hono adapter returns a Hono app that you mount with app.route().
npm install hono @hono/node-serverimport { serve } from "@hono/node-server";
import { CopilotRuntime, BuiltInAgent } from "@copilotkit/runtime/v2";
import { createCopilotHonoHandler } from "@copilotkit/runtime/v2/hono";
const runtime = new CopilotRuntime({
agents: {
default: new BuiltInAgent({ model: "openai/gpt-6-luna" }),
},
});
// Returns a Hono app with CopilotKit routes mounted at basePath
const endpoint = createCopilotHonoHandler({
runtime,
basePath: "/api/copilotkit",
});
// Serve the Hono app directly
serve({ fetch: endpoint.fetch, port: 4000 }, () => {
console.log("Listening at http://localhost:4000/api/copilotkit");
});Elysia (Bun)
Elysia runs on Bun and supports the Fetch API natively, so you use createCopilotRuntimeHandler directly.
bun add elysiaimport { Elysia } from "elysia";
import { CopilotRuntime, createCopilotRuntimeHandler, BuiltInAgent } from "@copilotkit/runtime/v2";
const runtime = new CopilotRuntime({
agents: {
default: new BuiltInAgent({ model: "openai/gpt-6-luna" }),
},
});
// Create a Fetch handler — Elysia passes the raw Request through
const handler = createCopilotRuntimeHandler({ runtime, cors: true });
new Elysia()
.all("/api/copilotkit/*", ({ request }) => handler(request))
.listen(4000);Lifecycle Hooks
All adapters support lifecycle hooks for cross-cutting concerns like authentication, logging, and response modification.
const handler = createCopilotRuntimeHandler({
runtime,
basePath: "/api/copilotkit",
hooks: {
// Before routing — auth, correlation IDs
onRequest: async ({ request, path, runtime }) => {
const token = request.headers.get("authorization");
if (!token) {
throw new Response("Unauthorized", { status: 401 });
}
},
// After routing — route-specific authorization
onBeforeHandler: async ({ request, route }) => {
if ("agentId" in route) {
console.log(`Handling ${route.method} for agent ${route.agentId}`);
}
},
// After handler — modify response headers
onResponse: async ({ response, request }) => {
const headers = new Headers(response.headers);
headers.set("x-request-id", crypto.randomUUID());
return new Response(response.body, {
status: response.status,
headers,
});
},
// On error — custom error responses
onError: async ({ error, request }) => {
console.error("Handler error:", error);
},
},
});| Hook | When | Can modify |
|---|---|---|
onRequest | Before routing | Throw Response to short-circuit |
onBeforeHandler | After routing, before handler | Access route info (method, agentId, threadId) |
onResponse | After handler | Return a new Response to replace it |
onError | On unhandled error | Log or produce a custom error response |
CORS Configuration
Fetch-native runtimes
Pass cors: true for permissive defaults (Access-Control-Allow-Origin: *), or provide a config object:
const handler = createCopilotRuntimeHandler({
runtime,
basePath: "/api/copilotkit",
cors: {
origin: "https://myapp.com",
credentials: true,
},
});Express
Pass cors: true for permissive defaults, or pass a cors options object:
createCopilotExpressHandler({
runtime,
basePath: "/api/copilotkit",
cors: {
origin: "https://myapp.com",
credentials: true,
},
});Hono
Pass a cors config with explicit origin:
createCopilotHonoHandler({
runtime,
basePath: "/api/copilotkit",
cors: {
origin: "https://myapp.com",
credentials: true,
},
});When using credentials: true, you must specify an explicit origin. A wildcard (*) is not allowed by the CORS spec.
Connecting Your Frontend
Once your runtime is running, point your frontend at it:
To check the runtime, run curl http://localhost:4000/api/copilotkit/info against a multi-route handler. The JSON response lists your agents under agents. Then open your app and send a message. The agent replies.
How is this guide?