All Blogs
Blog

Build an AI Chatbot with TanStack AI and TanStack Start

Build a streaming AI chatbot with TanStack AI, TanStack Start, and Claude that answers from your own FAQ with tool calling, rate limits, and a server-side key.

Last updated on November 27, 2026•—

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-chatbot

Now 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 zod

Let's go through each package:

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:

src/lib/knowledge.ts
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:

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:

src/lib/rate-limit.ts
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:

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:

src/routes/api.chat.ts
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

The handler

The chat call

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:

src/components/chat-widget.tsx
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:

Let's add some basic styles at the end of src/styles.css:

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:

src/routes/index.tsx
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 dev

Open 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

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.