Authentication
Pass user auth context from your frontend to the agent so it can scope tools, data, and decisions to the signed-in user.
You have a chat surface or a hook driving an agent and you want every agent run to know who the request came from. By the end of this guide, your frontend will forward a token, the runtime will pass it through, and your agent code will read the resulting user info on every turn.
When to use this#
- Multi-tenant apps where the agent reads or writes per-user data.
- Tool gating where some tools should only run for authorised users.
- Audit and billing where every run needs an identity to attribute it to.
- Session-aware UX where the agent's behaviour depends on the user's role or permissions.
If you don't need any of those, skip auth entirely. The agent runs anonymously and the frontend never has to care about tokens.
Frontend#
Pass your token via the headers prop on <CopilotKit>. CopilotKit forwards every request with that header attached.
import { CopilotKit } from "@copilotkit/react-core/v2";
<CopilotKit
runtimeUrl="/api/copilotkit"
headers={{
Authorization: `Bearer ${userToken}`,
}}
>
<YourApp />
</CopilotKit>
Backend#
Wire authentication into the V2 runtime via the onRequest hook. The hook runs before any agent code and operates on the raw Request, so it's the right place to read the Authorization header, run your verifier, and either let the request through or short-circuit with a 401:
import type { NextRequest } from "next/server";
import {
CopilotRuntime,
createCopilotRuntimeHandler,
} from "@copilotkit/runtime/v2";
const runtime = new CopilotRuntime({ agents: { default: myAgent } });
const handler = createCopilotRuntimeHandler({
runtime,
basePath: "/api/copilotkit",
hooks: {
onRequest: ({ request }) => {
const authHeader = request.headers.get("authorization");
if (!authHeader?.startsWith("Bearer ")) {
throw new Response(
JSON.stringify({ error: "unauthorized" }),
{ status: 401, headers: { "content-type": "application/json" } },
);
}
const token = authHeader.slice("Bearer ".length);
const user = verifyJwt(token); // your validation
// attach user to request-scoped context here
},
},
});
export const POST = (req: NextRequest) => handler(req);
export const GET = (req: NextRequest) => handler(req);
The V1 Next.js adapter (
copilotRuntimeNextJSAppRouterEndpoint) does not forward thehooksoption. UsecreateCopilotRuntimeHandlerfrom@copilotkit/runtime/v2directly when you need theonRequestgate.
Tool gating#
The most common reason to wire auth is so individual tools can decline to run. Read the resolved user inside the tool's handler and bail if the role doesn't match:
def delete_record(record_id: str, *, user: User):
if "admin" not in user.permissions:
raise PermissionError("admin role required")
# do the delete
This composes with Human in the loop: gate on auth first, surface a confirmation card next, execute last.
Security checklist#
- Always validate the token on the backend. Never trust the frontend's claim.
- Scope every read and write to the resolved user. Auth context only matters if you actually use it to filter data.
- Don't log raw tokens. Log the resolved user id (or
anonymous) instead. - Use HTTPS in production. The Bearer token is sensitive.
- Refresh strategy. Your frontend is responsible for rotating expired tokens before they reach the agent. CopilotKit doesn't refresh on your behalf.
