AI agents by framework / JavaScript and TypeScript
How to add an AI agent to a Next.js app
An AI agent in a Next.js app is a route handler that calls a model with tools, runs the tool calls the model makes against your own data layer as the signed-in user, and streams the result to a client component. The AI SDK covers the model loop and the chat UI; you supply the tools, authorization and limits. If the agent only needs to do what your pages already do, you can embed one instead.
What an agent in a Next.js app is made of
- A server endpoint: a route handler such as
app/api/chat/route.tsthat holds the model API key and calls the model. Model keys never go in client components or inNEXT_PUBLIC_variables. - Tools: typed functions the model may call, each wrapping an operation your app already has (a database query, a service call, an internal API).
- The agent loop: the model calls a tool, receives the result and decides the next step until it can answer. Cap the number of steps.
- A chat UI: a client component that streams messages and shows tool activity.
- Authorization and approval: tools act as the signed-in user, and actions that change data wait for the user to approve them.
Ways to add an agent to Next.js
| Approach | Good for | What you take on |
|---|---|---|
| AI SDK in a route handler | A custom agent with your own tools, model provider and UI. | Tool definitions, authorization in every tool, approval UI, rate and cost limits. |
| An agent framework (for example Mastra or LangGraph.js) | Long-running or multi-agent workflows with memory and orchestration. | Another layer to learn and deploy, plus everything in the row above. |
| Hosted answer-only chat widget | Questions about your docs or help center. | Keeping its content current. It does not act in your app. |
| Embedded in-app agent (Bunkhouse) | Letting signed-in users get tasks done through the pages and API you already have. | A script tag, an identity endpoint and hints for operations discovery cannot see. |
Build an agent with the AI SDK
The AI SDK is Vercel's TypeScript library for model calls, tool calling and chat UIs. The examples below use AI SDK 7 with the App Router. Install it with Zod for tool input schemas:
npm install ai @ai-sdk/react zodThe model string "anthropic/claude-sonnet-5.5" goes through the Vercel AI Gateway, which reads the API key from the AI_GATEWAY_API_KEY variable. To call a provider directly, install its package (for example @ai-sdk/openai) and pass its model instead.
1. The route handler
The handler refuses cross-site requests and authenticates the request before reading the body, then gives the model two tools. Each tool closes over the authenticated user, so the model can choose an order ID but never whose orders it reads or cancels. The condition isStepCount(5) lets the model call tools and continue for up to five steps. The setting toolApproval makes cancelOrder wait for the user. The option experimental_toolApprovalSecret signs approval requests so a client cannot forge one in the message history it sends back.
import {
convertToModelMessages,
createUIMessageStreamResponse,
isStepCount,
streamText,
toUIMessageStream,
tool,
type UIMessage,
} from "ai";
import { z } from "zod";
import { getCurrentUser } from "@/lib/auth"; // your existing session lookup
import { cancelOrder, listOrders } from "@/lib/orders"; // your existing data layer
export const maxDuration = 30;
export async function POST(req: Request) {
// Route handlers get no automatic CSRF protection: refuse cross-site requests.
if (req.headers.get("sec-fetch-site") !== "same-origin") return new Response("Forbidden", { status: 403 });
const user = await getCurrentUser();
if (!user) return new Response("Unauthorized", { status: 401 });
const { messages }: { messages: UIMessage[] } = await req.json();
const result = streamText({
model: "anthropic/claude-sonnet-5.5",
instructions: "You help the signed-in user manage their orders. Use the tools; never guess order data.",
messages: await convertToModelMessages(messages),
tools: {
listOrders: tool({
description: "List the signed-in user's recent orders",
inputSchema: z.object({ status: z.enum(["open", "shipped", "cancelled"]).optional() }),
execute: async ({ status }) => listOrders(user.id, { status }),
}),
cancelOrder: tool({
description: "Cancel one of the signed-in user's open orders",
inputSchema: z.object({ orderId: z.string() }),
execute: async ({ orderId }) => cancelOrder(user.id, orderId),
}),
},
toolApproval: { cancelOrder: "user-approval" },
experimental_toolApprovalSecret: process.env.TOOL_APPROVAL_SECRET,
stopWhen: isStepCount(5),
});
return createUIMessageStreamResponse({
stream: toUIMessageStream({ stream: result.stream }),
});
}2. The chat component
The useChat hook posts to /api/chat by default and streams the reply into its state. When the model calls cancelOrder, the tool part arrives in the state approval-requested. The user's answer is sent with addToolApprovalResponse, and the option sendAutomaticallyWhen resumes the conversation once every pending approval has a response.
"use client";
import { useChat } from "@ai-sdk/react";
import { lastAssistantMessageIsCompleteWithApprovalResponses } from "ai";
import { useState } from "react";
export function Agent() {
const [input, setInput] = useState("");
const { messages, sendMessage, addToolApprovalResponse } = useChat({
sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses,
});
return (
<div>
{messages.map((message) =>
message.parts.map((part, i) => {
const key = `${message.id}-${i}`;
if (part.type === "text") return <p key={key}>{part.text}</p>;
if (part.type === "tool-cancelOrder" && part.state === "approval-requested" && !part.approval.isAutomatic) {
const { id } = part.approval;
return (
<div key={key}>
<p>Cancel order {JSON.stringify(part.input)}?</p>
<button onClick={() => addToolApprovalResponse({ id, approved: true })}>Approve</button>
<button onClick={() => addToolApprovalResponse({ id, approved: false })}>Deny</button>
</div>
);
}
return null;
}),
)}
<form
onSubmit={(e) => {
e.preventDefault();
sendMessage({ text: input });
setInput("");
}}
>
<input aria-label="Message" value={input} onChange={(e) => setInput(e.currentTarget.value)} />
</form>
</div>
);
}Production checklist for Next.js
- Authorize in the handler and in every tool. Layouts and middleware are not an authorization boundary for route handlers; check the session in the handler and scope every query to that user, as the Next.js authentication guide recommends.
- Protect the handler against CSRF. Next.js compares
Originwith the host for Server Actions only (see data security). A route handler that authenticates with a cookie must reject cross-site requests itself, as the check of theSec-Fetch-Siteheader above does, or require a CSRF token that the chat transport sends. - Treat tool input and tool results as untrusted. The model chooses tool arguments, and data a tool returns (user-written text, emails, web pages) can contain instructions. Validate arguments with the schema and your own business rules, and require approval for anything irreversible.
- Limit cost. Cap steps, rate-limit the endpoint per user and set spending limits with your model provider.
- Allow for long responses. On serverless hosts, set the route's
maxDurationhigh enough for several model steps. - Keep secrets server-side. Model keys and the approval secret belong in server environment variables, never with the
NEXT_PUBLIC_prefix.
Option: embed an in-app agent with Bunkhouse
If the agent's job is to help signed-in users do work your Next.js app already supports, you may not need to build the tools, agent loop and chat UI yourself. Bunkhouse adds an Assistant pane to an existing web app with one script tag. When a user opens it, the assistant works with what the page already offers: buttons, links, form fields and tables, the API requests your app makes, a hints file you publish for operations it cannot see, and WebMCP tools your page declares.
The model writes small programs that run in a sandbox on the embed origin, not in your page. They can only call capabilities the assistant has discovered and your configuration allows. Write actions are shown to the user for review before they run, the model never sees credentials, and your Next.js backend keeps enforcing its own authorization on every request.
In Next.js, render the loader with next/script and strategy="beforeInteractive" in the root layout, so it loads once per document and before your app makes its first requests. For signed-in users, add a GET /api/agent-identity route handler that signs a short-lived token for the user your session already authenticated; the signing secret stays in a server environment variable.
import Script from "next/script";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<Script src="/agent-identity.js" strategy="beforeInteractive" />
<Script
src="https://embed.bunkhouse.ai/embed.js"
data-public-key="pk_YOUR_SITE_PUBLIC_KEY"
strategy="beforeInteractive"
/>
</head>
<body>{children}</body>
</html>
);
}The tested Next.js integration guide has the complete code for each session mode (signed identity token, server mint and anonymous), CSRF headers and Content Security Policy settings.
When Bunkhouse fits, and when to build it yourself
- Bunkhouse fits when users want tasks done inside your existing pages, such as filtering, editing or submitting through the controls and API you already have, and you would rather not write and maintain a tool definition for each action, a sandbox for model-written code, an approval UI and usage metering.
- Build it yourself when the agent must run without a browser page (background jobs, email, chat platforms, scheduled work), when you need to choose the model provider, use your own keys or run inference on your own infrastructure, or when the conversation must be part of your own UI components.
- Plan for the limits: discovery cannot see server-only routes, workflows the user has not visited, closed shadow roots or cross-origin frames (describe those in a hints file); some controls need a real user gesture; password, payment and file fields are never read, and you can mark other content private.
- Cost: production use is $49 per month, including $20 of usage credit per paid billing period, then $1 per million input tokens and $3 per million output tokens. See billing.
Try it on your Next.js app first
A coding agent such as Claude Code, Codex or Cursor can run a free, disposable agent trial on a dummy page of your Next.js app. No account, card or model API key is needed: your coding agent acts as the assistant's model. A trial lasts 24 hours and allows 100 turns. Give your agent this instruction, changing the address if your app runs elsewhere:
Read https://api.bunkhouse.ai/agent-trial.md and follow it to run a Bunkhouse agent trial on my dummy Next.js page at http://localhost:3000.Use a page with disposable data: everything the assistant reads is sent to your agent.
The trial evaluation checklist shows how to test a read, a rejected write and an approved change, and what a trial does not prove about production use.