Add an AI assistant to your Next.js app, with limits that protect your bill
Build a chat assistant with Claude that streams its answers into the page, keeps your API key on the server, remembers each visitor’s conversation, stops when a visitor leaves, and can never spend more than you decided. Every failure, from a missing key to a busy provider, gets a clear message.
Tested step by step on with Next.js 16.4.6, Prisma 7.10.1 and the Anthropic SDK 1.12.0
An AI assistant is one of the most requested features in any SaaS, and one of the easiest to get wrong: an API key shipped to the browser, an answer that appears all at once after twenty silent seconds, a bill nobody capped, and an error page the day the provider is busy. This guide builds one properly, on a real app, with Claude.
You’ll add an “Ask about your tasks” page to a task list. It streams Claude’s answer into the page as it’s written, remembers each visitor’s conversation, and stops generating when the visitor leaves. It enforces two limits: questions per visitor per day, and tokens for the whole app per day, so the most it can cost is a number you chose. Every step was run on a fresh create-next-app project and a fresh shadcn init project, with Next.js 16.4, Prisma 7.10 and the Anthropic SDK 1.12. The test talks to a local stand-in that answers exactly as Anthropic’s API does (the same streaming events and error responses), so the outages, refusals and limits below were triggered on purpose without spending anything. Claude’s real answers will be worded differently from the examples.
Before you start
- The tasks app from Next.js 16 + Prisma 7 + Postgres, steps 1 to 11. It has a
/taskspage and a database. The assistant will read the tasks and save its conversations there. - An account on the Claude Platform at platform.claude.com, with a few dollars of credit. The API is billed by usage, separately from a Claude chat subscription. Step 11 works out what this assistant costs.
- Run every command from the project’s folder.
1. Get an API key, and keep it secret
Open platform.claude.com/settings/keys, create a key, and copy it (it’s shown once). Add it at the end of .env, the file the Prisma guide made for your database address:
- Anyone with this key can spend your credit. It goes in
.env(which git ignores, so it never reaches GitHub) and in your host’s settings, and never in code or in a variable starting withNEXT_PUBLIC_, which Next.js copies into the JavaScript every visitor downloads. - Every call in this guide is made from your server. The browser only ever talks to your own app.
2. Install the SDK
@anthropic-ai/sdkis Anthropic’s official library for calling Claude.@1keeps you on version 1, which this guide was tested with.server-onlymakes the build fail if a file marked with it is ever imported into a browser component. You’ll put it at the top of the file that holds the key’s client.
3. Make your first call
Before building anything, check the key works with a ten-line script. Create scripts/hello-claude.ts:
It prints one friendly sentence, then a line like (25 tokens in, 60 out). Every call is billed by tokens, pieces of words: what you send (in) and what Claude writes (out). The request itself is the whole API in miniature:
model: which Claude answers.claude-opus-5-5is Anthropic’s current default model.max_tokens: the most the answer may use. It’s a hard stop, so it doubles as a cost cap per answer.output_config: { effort: "low" }: how hard Claude thinks before answering. Claude Opus 5.5 can think before it answers;lowkeeps that short, which suits chat. Thinking counts as output tokens.messages: the conversation so far. Claude remembers nothing between calls, so you send the history every time.
If it prints authentication_error instead, the key in .env is wrong or has a typo. If it mentions your credit balance, add credit on the Claude Platform and run it again.
4. Store conversations and usage
Two new tables: the messages of each visitor’s conversation, and how much each visitor (and the whole app) has used today. Add them at the end of prisma/schema.prisma:
- A
ChatMessagebelongs to a visitor: a random id kept in a cookie, since this app has no accounts. With accounts (the Better Auth guide), use the user’s id instead, and their conversation follows them to every device. - An
AiUsagerow counts one thing for one day:visitor:<id>for a visitor,appfor everyone together.
5. One place for the client and the limits
Create lib/ai.ts:
new Anthropic()readsANTHROPIC_API_KEYfrom the environment by itself.import "server-only"guarantees this file, and the key it uses, never reach the browser.- Every limit lives here, with a name, so you can see at a glance what the assistant may spend. Step 11 turns them into money.
- The system prompt tells Claude what it is and gives it the tasks. Task titles are typed by users, so the prompt says to treat them as data: someone could add a task titled “Ignore your instructions and…”. That can’t do much harm here, because the assistant can only talk. Never give a model the power to act (delete, send, pay) without checking each action yourself, exactly as a server action checks its caller.
6. Count questions and tokens
Create lib/ai-budget.ts:
startQuestionruns before every question. It adds one to the visitor’s count for today and reads the result in one SQL statement, so a visitor firing ten questions at once can’t have them all read “29” and slip through. Then it checks the app’s token total for today.recordTokensruns after every answer, with the real numbers the API reports, and adds them to the visitor’s and the app’s totals.- The app’s limit is checked before a question, so answers already being written can take it slightly past the limit, by at most one answer each (
MAX_ANSWER_TOKENS). That’s the price of not making everyone wait in line. - Clearing cookies makes a new visitor, which resets the per-visitor count. That’s why the app-wide budget exists: it’s the limit nobody can get around, and it’s what protects your bill.
7. The route that streams the answer
A server action returns one value at the end, but an answer should appear as it’s written. A route handler can return a stream. Create app/api/chat/route.ts:
Read it top to bottom; it’s the whole feature:
- No key, no call. Without
ANTHROPIC_API_KEY, the visitor sees “The assistant isn’t set up yet.” and your terminal says why. - Check the question on the server: a string, not empty, at most 2,000 characters. The input box has a
maxLengthtoo, but anyone can send a request without your page. - The visitor’s cookie is
httpOnly(page scripts can’t read it) and made on their first question. - Limits come before the call, and a refused question returns
429with a sentence a person can understand. - History: the last 20 messages, oldest first, starting with a question. Sending the whole history every time is what lets Claude follow a conversation, and capping it is what keeps a long conversation from costing more with every question.
anthropic.beta.messages.stream(…)starts the answer.fallbacks: "default"(with itsbetasline) asks the API to retry on another model if Claude Opus 5.5 declines a request for safety reasons, instead of simply stopping.- Leaving stops the bill. When the visitor closes the page,
request.signalfires andstream.abort()stops Claude mid-answer, so you don’t pay for text nobody will read. - The response is a stream of lines, one small JSON event per line:
textpieces as they’re written, thendone,cut(the answer hitmax_tokens) orerror. One JSON event per line is easy to read in the browser and impossible to confuse with the answer’s own text. - After the answer, the tokens it really used are recorded, and the question and answer are saved together, only if it succeeded. A refusal (
stop_reasonis"refusal") is reported, not saved. - Errors are caught and turned into a plain sentence. The SDK already retries a busy or failing API twice before giving up; the details go to your terminal with
console.error, never to the visitor.
8. The chat page
Three files in a new app/assistant folder. First, the action that forgets a conversation, app/assistant/actions.ts:
The chat itself is a client component, because it updates as the answer arrives. Create app/assistant/chat.tsx:
askadds the question and an empty answer straight away, then fills the answer in piece by piece:response.bodyis read with a reader, split into lines, and eachtextevent is added to the last message.- If anything fails, the question goes back into the box and a sentence explains what happened, so nothing typed is lost. A failed question wasn’t saved on the server either, so a reload shows the same conversation.
- The answer is shown as text (
{line.content}), never as HTML, so nothing Claude writes can run in the page. The system prompt asks for plain text for the same reason: Markdown would show its**marks. - “Start over” calls the action first, then clears the screen.
Finally the page, app/assistant/page.tsx, which loads the saved conversation:
The conversation depends on the visitor’s cookie, so it’s read inside <Suspense>: the heading is ready instantly and the messages stream in a moment later, as the tasks list does.
9. Try it
- Open http://localhost:3000/assistant and ask “Which of my tasks aren’t done yet?”. The button says “Answering…” and the answer appears a few words at a time, naming the tasks from your list.
- Ask a follow-up, like “Which one should I do first?”. Claude knows what “one” means, because the history went with the question.
- Reload the page: the conversation is still there. “Start over” clears it.
- Tick a task on /tasks and ask again: the assistant sees the change, because the tasks are read fresh for every question.
10. When things go wrong
Each of these was triggered on purpose while testing this guide, and each shows the visitor a sentence instead of a broken page:
- No key (
ANTHROPIC_API_KEYmissing): “The assistant isn’t set up yet.” The terminal saysThe assistant needs ANTHROPIC_API_KEY in .env. Restartnpm run devafter editing.env. - A wrong or revoked key: “The assistant isn’t set up correctly.” The terminal shows the
authentication_error. - The API is busy or down (an
overloaded_error, or no connection): the SDK tries three times in all, then the visitor sees “The assistant is unavailable right now. Try again in a minute.”, with their question back in the box. - Claude declines and no fallback model answers either: “The assistant can’t help with that one.”
- The answer reaches
MAX_ANSWER_TOKENS: what was written is kept, followed by “… (the answer was cut short)”. - The visitor leaves mid-answer: generation stops, nothing is saved, and only the part already written is billed.
- Too many questions (30 today): “That’s all the questions for today. Come back tomorrow.” The app’s budget is spent: “The assistant has answered all it can for today. Try again tomorrow.” Both reset at midnight UTC.
- In these cases the browser’s console also prints “Failed to load resource: the server responded with a status of 429” (or 503 for a missing key). That’s the browser noting the status code the route chose on purpose, not a bug.
11. What it costs
At the time of writing (November 2026), Claude Opus 5.5 costs $4 per million input tokens and $20 per million output tokens; check the pricing page for today’s prices. Here’s what that means for this assistant:
- A typical question sends the instructions, your tasks and the recent conversation, perhaps 1,500 tokens ($0.006), and gets a short answer with a little thinking, perhaps 300 tokens ($0.006). About one cent. The line
hello-claude.tsprinted shows real counts for a tiny request, and theAiUsagetable holds the real totals for your app. - The most one answer can cost is set by
MAX_ANSWER_TOKENS: 4,000 output tokens is $0.08, plus its input. - The most a day can cost is set by
APP_TOKENS_PER_DAY: 500,000 tokens is at most $10 even if every token were output, and nearer $3 for a normal mix, plus at most one answer per question already in progress when the limit was reached. - Change the numbers in
lib/ai.tsto fit your budget.
12. Deploy
On Vercel, add ANTHROPIC_API_KEY under Settings → Environment Variables for Production, then redeploy: variables are read when the app starts. Run npx prisma migrate deploy against your production database first, as in the Prisma guide, so the two new tables exist. Use a separate key for production, so you can revoke a leaked development key without taking the live site down.
If something goes wrong
Could not resolve authentication methodwhen runninghello-claude.ts:.envhas noANTHROPIC_API_KEYline, or the script was run from another folder. Run it from the project’s folder.The table "public.ChatMessage" does not exist: run step 4’s two commands, then restartnpm run dev.- The answer appears all at once instead of word by word: something between the server and the browser is holding the response back. Locally it streams; behind a proxy, make sure it doesn’t buffer responses.
- “The assistant isn’t set up yet.” although the key is in
.env: restartnpm run dev;.envis read when the server starts. - “That’s all the questions for today.” while you’re testing: delete your own row (
npx prisma studio, tableAiUsage), or raiseVISITOR_QUESTIONS_PER_DAYwhile developing.
Questions people ask
How much does a Claude assistant cost to run?
For this one, about a cent a question with Claude Opus 5.5 at November 2026 prices: roughly 1,500 tokens in and 300 out. Two limits set your worst case. MAX_ANSWER_TOKENS caps a single answer, and APP_TOKENS_PER_DAY caps the whole app, so 500,000 tokens a day is at most $10.
Can I call the Claude API from the browser?
Don’t. Anyone who has the key can spend your credit, and anything sent to a browser can be read. Keep ANTHROPIC_API_KEY in .env and in your host’s settings, never in a NEXT_PUBLIC_ variable, and make every call from your server. The browser only ever talks to your own route.
How do I stream Claude’s answer in Next.js?
Use a route handler, not a server action. A server action returns one value at the end, while a route handler can return a stream. The route passes Claude’s text on as it arrives, and the chat component reads response.body piece by piece, adding each bit to the last message.
What happens when the Claude API is busy?
The SDK tries three times in all. If it still can’t get through, the visitor sees “The assistant is unavailable right now. Try again in a minute.”, and their question goes back in the box so nothing they typed is lost. Every failure in this guide was triggered on purpose while testing it.
Where to go next
- Add accounts with Better Auth and key the conversation and the limits on the user’s id: their history follows them, and the per-person limit can’t be reset by clearing cookies.
- Give the assistant tools, so it can add or tick tasks for the visitor, with every tool call checked by your code first. The security guide covers the checks every server-side action needs.
- Read Anthropic’s guide to streaming, and to refusals and fallbacks.