Most websites answer the same questions over and over. How much does it cost? Is there a free trial? Does it work offline? The answers are somewhere on the site, but visitors have to find the right page first, and many of them give up before they do.
A small chatbot fixes that. Visitors ask a question in plain words and get a short answer from your own content. It works on a SaaS landing page, a docs site, a store, or even a portfolio. You can build one with TanStack AI, the type-safe AI SDK from the TanStack team. It works with any provider and plugs straight into TanStack Start.
In this tutorial, we will learn how to build a streaming AI chatbot with TanStack AI and TanStack Start. We will give it a system prompt and a tool that searches our FAQ, so it answers from real data instead of guessing. It will stream answers from a server route, keep the API key on the server, and guard the endpoint with a rate limit and a size limit.
Project Setup
We will start from a new TanStack Start app. If you already have a Start app, you can skip this step.
npx @tanstack/cli@latest create my-chatbot
cd my-chatbotNow let's install TanStack AI. We need the core package, the React bindings, an adapter for our provider (we will use Anthropic's Claude), and Zod for the tool schema:
npm install @tanstack/ai @tanstack/ai-react @tanstack/ai-anthropic zodLet's go through each package:
@tanstack/ai: The core. It haschat(), tools, and the streaming helpers we use on the server.@tanstack/ai-react: TheuseChathook and the connection adapters for the browser.@tanstack/ai-anthropic: The Anthropic adapter for Claude models. You can swap it for@tanstack/ai-openai,@tanstack/ai-gemini, or@tanstack/ai-openrouterlater. The rest of the code stays the same.zod: Describes the input of our tool so the model knows how to call it.
Environment Variables
Create a .env file in the root of the project:
ANTHROPIC_API_KEY=sk-ant-...You can create a key in the Claude Console. The Anthropic adapter reads ANTHROPIC_API_KEY from the environment. The name has no VITE_ prefix, and that matters. Vite only sends variables that start with VITE_ to the browser. The key only exists on the server, which is where our chat route runs. We will check this at the end.
Remember to add .env to your .gitignore.
Knowledge Data
The chatbot can only answer well if it knows about our product. In this tutorial, we will use a fictional note-taking app called Acme Notes. Let's put what the bot should know in one file:
export const site = {
name: 'Acme Notes',
description: 'A note-taking app for teams, with real-time editing, search, and offline mode.',
supportUrl: 'https://acme-notes.example.com/support',
};
export const faqTopics = ['pricing', 'features', 'account'] as const;
export const faqs = [
{
topic: 'pricing',
question: 'How much does Acme Notes cost?',
answer: 'The Free plan is $0 and includes 3 workspaces. The Pro plan is $8 per user per month and adds unlimited workspaces and version history.',
},
{
topic: 'pricing',
question: 'Is there a free trial?',
answer: 'Yes. Every new account gets a 14-day Pro trial, and no credit card is needed.',
},
{
topic: 'features',
question: 'Does it work offline?',
answer: 'Yes. The desktop and mobile apps keep working offline and sync when you reconnect.',
},
{
topic: 'features',
question: 'Can I import my notes?',
answer: 'Yes. You can import Markdown files, plus Notion and Evernote exports.',
},
{
topic: 'account',
question: 'How do I delete my account?',
answer: 'Go to Settings, then Account, and click Delete account. Your data is removed within 30 days.',
},
] satisfies Array<{ topic: (typeof faqTopics)[number]; question: string; answer: string }>;
export function buildSystemPrompt() {
return [
`You are the help assistant on the ${site.name} website.`,
`About ${site.name}: ${site.description}`,
'Answer questions about the product in 2 to 4 short sentences.',
'Before you answer a product question, call the get_faq tool and answer from what it returns.',
`If a question is not about ${site.name}, politely say you can only help with ${site.name}.`,
`Never invent features, prices, or policies. If the FAQ does not cover it, point people to ${site.supportUrl}.`,
].join('\n');
}Replace the values with your own product. Let's look at the pieces:
site: Short facts about your product. The system prompt includes them, so they go into every request. Keep them short, because long prompts cost more tokens on each message.faqTopics: The topics we group our FAQ by. Theas constturns it into a fixed list, so we can reuse it in the tool schema later.faqs: The questions and answers the bot can use. We do not put them in the prompt. The model gets them through a tool when it needs them, so the prompt stays small even with 200 entries.satisfieschecks that every entry uses a valid topic.buildSystemPrompt: The rules for the assistant. It says who it speaks for, how long answers should be, when to use the tool, and what to do with off-topic questions. The rule "never invent features, prices, or policies" is the most important one. You do not want the bot to promise a discount you never offered.
The FAQ is a simple array here, but it could come from anywhere: Markdown files, your CMS, or a database table.
Rate Limiting
Our chat endpoint is public and every request costs money. Before we build it, let's add a simple rate limiter, so one visitor cannot drain your Anthropic credits:
const WINDOW_MS = 60_000;
const MAX_REQUESTS = 10;
const hits = new Map<string, { count: number; resetAt: number }>();
export function rateLimit(key: string) {
const now = Date.now();
const entry = hits.get(key);
if (!entry || entry.resetAt <= now) {
hits.set(key, { count: 1, resetAt: now + WINDOW_MS });
return { ok: true, retryAfter: 0 };
}
entry.count++;
if (entry.count > MAX_REQUESTS) {
return { ok: false, retryAfter: Math.ceil((entry.resetAt - now) / 1000) };
}
return { ok: true, retryAfter: 0 };
}Let's go through each piece:
WINDOW_MSandMAX_REQUESTS: Each visitor gets 10 messages per minute. That is plenty for a real conversation.hits: A map from a key (the visitor's IP) to a counter and a reset time.retryAfter: How many seconds until the window resets. We send it back in theRetry-Afterheader.
This limiter lives in memory, so it resets when the server restarts. Each server instance also has its own count. That is fine for a small site on one server. If you deploy to serverless, move the counter to a shared store like Redis or Upstash.
Creating the Chat Server Route
This is the core of the chatbot. TanStack Start server routes let us handle a POST request in the same file-based routing we use for pages. Create the file:
import { createFileRoute } from '@tanstack/react-router';
import { getRequestIP } from '@tanstack/react-start/server';
import {
chat,
chatParamsFromRequest,
maxIterations,
toolDefinition,
toServerSentEventsResponse,
} from '@tanstack/ai';
import { anthropicText } from '@tanstack/ai-anthropic';
import { z } from 'zod';
import { buildSystemPrompt, faqs, faqTopics } from '../lib/knowledge';
import { rateLimit } from '../lib/rate-limit';
const MAX_MESSAGES = 20;
const MAX_PAYLOAD_CHARS = 8_000;
const getFaq = toolDefinition({
name: 'get_faq',
description: 'Get questions and answers about the product from the official FAQ.',
inputSchema: z.object({
topic: z
.enum(faqTopics)
.optional()
.meta({ description: 'Only return entries about this topic. Leave it out to get all of them.' }),
}),
}).server(async ({ topic }) => {
if (!topic) return faqs;
return faqs.filter((faq) => faq.topic === topic);
});
export const Route = createFileRoute('/api/chat')({
server: {
handlers: {
POST: async ({ request }) => {
const ip = getRequestIP({ xForwardedFor: true }) ?? 'unknown';
const limit = rateLimit(ip);
if (!limit.ok) {
return new Response('Too many messages. Try again in a minute.', {
status: 429,
headers: { 'Retry-After': String(limit.retryAfter) },
});
}
const { messages, threadId, runId } = await chatParamsFromRequest(request);
const history = messages.filter((message) => message.role !== 'system');
if (
history.length > MAX_MESSAGES ||
JSON.stringify(history).length > MAX_PAYLOAD_CHARS
) {
return new Response('This chat is too long. Refresh to start a new one.', {
status: 413,
});
}
const stream = chat({
adapter: anthropicText('claude-haiku-5-5'),
messages: history,
threadId,
runId,
systemPrompts: [buildSystemPrompt()],
tools: [getFaq],
agentLoopStrategy: maxIterations(3),
modelOptions: { max_tokens: 400 },
});
return toServerSentEventsResponse(stream);
},
},
},
});There is a lot here, so let's go step by step.
The tool
toolDefinition: Describes a function the model can ask us to run.nameanddescriptiontell the model what it does.inputSchemais a Zod schema for the arguments. Here it is an optionaltopic. We usez.enum(faqTopics), so the model can only pick a topic that exists, and.meta({ description })explains the field to the model..server(...): The code that runs on our server when the model calls the tool. It returns our FAQ entries, filtered by topic if the model asked for one. In a bigger app, this is where you would search your docs or query a database. TanStack AI sends the result back to the model, and the model writes the answer with it.
The handler
createFileRoute('/api/chat')withserver.handlers.POST: The file nameapi.chat.tsmaps to the/api/chatURL. There is no component, only aPOSThandler that gets therequest.getRequestIP({ xForwardedFor: true }): Reads the visitor's IP, so each visitor gets their own rate limit. Only turn onxForwardedForwhen you run behind a proxy or CDN that sets the header (Vercel, Netlify, Cloudflare). Otherwise, anyone can fake it.chatParamsFromRequest(request): Reads the JSON body thatuseChatsends and checks it. It gives usmessages,threadId, andrunId. If the body is not valid, it throws a400response, and TanStack Start returns it for us.messages.filter(...): The messages come from the browser, so we cannot trust them. Someone could send their ownsystemmessage to override our rules. We drop those messages and only use our system prompt.- The size check: We reject chats with more than 20 messages or more than 8,000 characters. Every message is sent to the model again on each turn, so a long chat costs more and more. This also stops someone from pasting a book into the input.
The chat call
adapter: anthropicText('claude-haiku-5-5'): Which provider and model to use. Claude Haiku is Anthropic's fastest and cheapest model, and it is more than good enough to answer questions from a FAQ. The adapter readsANTHROPIC_API_KEYon the server.systemPrompts: Our rules and product facts frombuildSystemPrompt().tools: [getFaq]: The tools the model can call. TanStack AI runs the agent loop for us: the model calls the tool, we run it, and the model gets the result.agentLoopStrategy: maxIterations(3): The loop stops after 3 rounds at most, so a confused model cannot call tools forever.modelOptions: { max_tokens: 400 }: A cap on the answer length. These options are typed for the model you picked, so your editor shows the Anthropic options here.toServerSentEventsResponse(stream): Turns the stream into a Server-Sent Events response. The browser gets the answer token by token instead of waiting for the full text.
Building the Chat Widget
Now the browser side. useChat from @tanstack/ai-react keeps the messages, sends new ones to our route, and updates the UI while the answer streams in:
import { useState } from 'react';
import { fetchServerSentEvents, useChat } from '@tanstack/ai-react';
const SUGGESTIONS = ['How much does it cost?', 'Does it work offline?'];
export function ChatWidget() {
const [open, setOpen] = useState(false);
const [input, setInput] = useState('');
const { messages, sendMessage, isLoading, error } = useChat({
connection: fetchServerSentEvents('/api/chat'),
threadId: 'help-chat',
});
function send(text: string) {
const value = text.trim();
if (!value || isLoading) return;
sendMessage(value);
setInput('');
}
if (!open) {
return (
<button className="chat-toggle" onClick={() => setOpen(true)}>
Ask a question
</button>
);
}
return (
<div className="chat-panel">
<header>
<strong>Acme Notes help</strong>
<button onClick={() => setOpen(false)}>Close</button>
</header>
<div className="chat-messages">
{messages.length === 0 &&
SUGGESTIONS.map((suggestion) => (
<button key={suggestion} onClick={() => send(suggestion)}>
{suggestion}
</button>
))}
{messages.map((message) => (
<div key={message.id} className={`chat-message ${message.role}`}>
{message.parts.map((part, index) => {
if (part.type === 'text') return <p key={index}>{part.content}</p>;
if (part.type === 'tool-call' && part.state !== 'complete') {
return <em key={index}>Checking the FAQ...</em>;
}
return null;
})}
</div>
))}
{error && <p className="chat-error">Something went wrong. Try again in a minute.</p>}
</div>
<form
onSubmit={(event) => {
event.preventDefault();
send(input);
}}
>
<input
value={input}
maxLength={500}
placeholder="Ask a question..."
onChange={(event) => setInput(event.target.value)}
/>
<button type="submit" disabled={isLoading || !input.trim()}>
Send
</button>
</form>
</div>
);
}Let's go through the most important parts:
fetchServerSentEvents('/api/chat'): The connection adapter. It sends the chat to our route withPOSTand reads the SSE stream back. Note that we only pass a URL. The browser never sees the API key.threadId: A name for this conversation.useChatrequires it, and it reaches our route asthreadId. One fixed name is fine for a single widget.messages: The whole chat, with user and assistant messages. Each message haspartsinstead of one string, because one answer can mix text and tool calls.part.type === 'text': Text parts have their text inpart.content. It grows while the answer streams.part.type === 'tool-call': Shows up when the model callsget_faq. We show a small "Checking the FAQ..." note until the call iscomplete, then the text answer takes over.sendMessage(value): Adds the user message and starts the request.isLoadinganderror: We disable the button while an answer streams. If the route returns an error (like our429),erroris set and we show a friendly note.maxLength={500}: Stops long questions in the browser. The server check is the real guard, because anyone can call the API directly.
Let's add some basic styles at the end of src/styles.css:
.chat-toggle,
.chat-panel {
position: fixed;
right: 1.5rem;
bottom: 1.5rem;
}
.chat-panel {
display: flex;
flex-direction: column;
width: 22rem;
height: 30rem;
background: white;
border: 1px solid #ddd;
border-radius: 12px;
}
.chat-panel header,
.chat-panel form {
display: flex;
justify-content: space-between;
gap: 0.5rem;
padding: 0.75rem;
}
.chat-messages {
flex: 1;
overflow-y: auto;
padding: 0.75rem;
}
.chat-message.user {
text-align: right;
}Adding the Widget to the Page
Finally, let's render the widget on our home page:
import { createFileRoute } from '@tanstack/react-router';
import { ChatWidget } from '../components/chat-widget';
export const Route = createFileRoute('/')({ component: Home });
function Home() {
return (
<main>
<h1>Acme Notes</h1>
<p>Notes for teams, with real-time editing and offline mode.</p>
<ChatWidget />
</main>
);
}If you want the chatbot on every page, render <ChatWidget /> in the body of src/routes/__root.tsx instead.
Testing It
Start the dev server:
npm run devOpen http://localhost:3000, click Ask a question, and try "How much does it cost?". You will see the "Checking the FAQ..." note for a moment, then the answer streams in with the prices from knowledge.ts. Try an off-topic question too, like "Write me a poem". The bot should politely decline.
You can also test the guards from the terminal. Send more than 10 messages in a minute and the route answers with 429 Too Many Requests. A chat over the size limit gets 413.
Last, let's make sure the key never reaches the browser. Build the app and search the output for the real key from .env:
npm run build
grep -rF "$(grep ANTHROPIC_API_KEY .env | cut -d= -f2)" dist || echo "API key not found in the build"We search for the full key on purpose. A search for sk- finds false matches in minified CSS code, like mask-type. The key is not in the server bundle either, because the server reads process.env.ANTHROPIC_API_KEY at runtime. Set it in your hosting provider's environment settings when you deploy.
Going Further
- Change the provider: Swap
anthropicTextforopenaiTextfrom@tanstack/ai-openai(or any other adapter). You can also tryclaude-sonnet-5-5if you want smarter answers and do not mind the higher cost. The route, tool, and widget stay the same. - Better rate limits: Use Redis or Upstash for a shared limit, and add a daily spending limit in your provider's dashboard as a safety net.
- Search real docs: Replace the FAQ array with a search over your Markdown docs or your CMS. For large docs, use embeddings and a vector search inside the tool.
- More tools: Add a
get_planstool that reads live prices from your billing provider, or aget_statustool that checks your status page.
If you want to put the chatbot behind a login or charge for it, check my posts on authentication with Better Auth and Drizzle and Stripe subscriptions in TanStack Start.
Conclusion
In this tutorial, we built an AI chatbot with TanStack AI and TanStack Start. We gave it a system prompt and a get_faq tool, so it answers from our own content. We streamed answers from a server route with chat() and toServerSentEventsResponse, and rendered them with useChat. We also kept the API key on the server, and protected the endpoint with a rate limit, a size limit, and a filter for injected system messages.
Now visitors can ask about your product and get an answer right away, instead of digging through every page. Swap in your own FAQ and you can drop this widget into any site, from a SaaS landing page to a docs site or a portfolio.