Next.js AI chatbot tutorial with no key on your server
This Next.js AI chatbot tutorial removes app/api/chat/route.ts and the provider key it holds. Each answer counts against the visitor's own AI account, and your server keeps only the MCP tools it hosts.
Published on
This Next.js AI chatbot tutorial removes app/api/chat/route.ts and the provider key it holds. Each answer counts against the plan, credits or key of the AI account the visitor picked in AI Wallet, and your server keeps only the MCP tools it hosts. The usual build pays its provider on every visitor message: one message of about 1,500 input and 300 output tokens costs $0.006 on Claude Sonnet 5.5 at the list prices a November 2026 tutorial quotes. You rebuild the same chat on Next.js 16 with the App Router (the app/ directory routing of Next.js) and AI Connect, the open source SDK we publish on npm. You install two packages, add one client provider, one chat panel and one public site key, then run 12 visitor checks before you ship.
Key takeaways:
- The four AI Connect packages reached npm under the
@tensorpassscope on 16 November 2026; the changelog lists version 0.1.7 on 24 November 2026.- Next.js inlines every
NEXT_PUBLIC_variable into the browser bundle atnext build, so the one key left in your environment is the public site key (tpk_...).create-next-appenables Cache Components by default for App Router projects, and auseChatcall without a fixed id fails that prerender onMath.random().- The reference MCP server in our docs allows 60 requests a minute per visitor address, and the tool loop stops at 6 steps by default.
What a Next.js AI chatbot tutorial keeps on the server
The tutorials ranking for this query in November 2026 share one shape. A route handler at app/api/chat/route.ts calls streamText from the AI SDK (Vercel's TypeScript library for model calls). useChat streams the answer into a client component. ANTHROPIC_API_KEY sits in .env.local. One Next.js 16 tutorial, updated on 17 November 2026, estimates roughly $3 to $5 per 1,000 chats on Sonnet with turns of about 800 tokens. Another, pinned to Next.js 16.4.0 and AI SDK 7, prices one message at $0.012 on Claude Opus 5.5 and $0.0003 on Haiku 5.5. Your provider account pays for each of those messages, including the ones a script sends.
The route handler in a Next.js AI chatbot tutorial
The route holds the key because a variable without the NEXT_PUBLIC_ prefix exists only in the Node.js environment. Moving the call into the page with a provider key would ship that key in the bundle. AI Connect moves the call into the page with no provider key at all: you build the provider with the AiConnect client's fetch, and the request goes to the visitor's wallet.
| Route handler build | AI Connect build | |
|---|---|---|
| Model call runs in | app/api/chat/route.ts on your server | A client component in the visitor's browser |
Secret in .env.local | Provider key (sk-ant-...) | None; the site key tpk_... is public |
| Account billed per answer | Your provider account | The visitor's AI account |
| Server route left | Chat route and its rate limiter | MCP relay at /api/mcp |
| Model choice | You pin it in code | The visitor picks it in AI Wallet |
Create the app and install AI Connect
Next.js 16 requires Node.js 20.9 or later. The recommended defaults of create-next-app set up TypeScript, ESLint, Tailwind CSS, the App Router and Cache Components.
npx create-next-app@latest my-chat
cd my-chat
npm install @tensorpass/aiconnect @tensorpass/aiconnect-reactThe two packages need React 19 or later, which the Next.js 16 template ships. To try the chat locally you need Chrome with AI Wallet (our browser extension that holds the visitor's AI accounts) and one connected account. If you are still choosing an install route, the hub page on how to add an AI chatbot to your website compares the options.
Add the client provider and the site key
AiConnectProvider uses React state and the browser, so it lives in a 'use client' component rendered in app/layout.tsx. A lazy useState initializer builds one client per page load.
'use client';
import { useState } from 'react';
import type { ReactNode } from 'react';
import { AiConnect } from '@tensorpass/aiconnect';
import { AiConnectProvider } from '@tensorpass/aiconnect-react';
import '@tensorpass/aiconnect-react/styles.css';
function createClient() {
return new AiConnect({
siteKey: process.env.NEXT_PUBLIC_TENSORPASS_SITE_KEY,
signInCallback: '/aiconnect/callback',
});
}
export default function AiModeProvider({ children }: { children: ReactNode }) {
const [client] = useState(createClient);
return <AiConnectProvider client={client}>{children}</AiConnectProvider>;
}The site key is the public identifier that adds Sign in with TensorPass to the connect window. npx @tensorpass/aiconnect site-key <domain> creates it and prints where it goes. It works on localhost at once. A visitor without AI Wallet gets the wallet's install button and Sign in with OpenRouter, with or without a site key. Both sign ins open in a popup with PKCE and return to app/aiconnect/callback/page.tsx, a page that calls finishSignIn() and carries robots: { index: false }.
The chat panel loads through next/dynamic with ssr: false. McpToolSource('/api/mcp') resolves its relative URL against the page address, which exists in the browser only. Inside the panel, useAiChat({ system, tools }) returns the turns, send, busy and error. To keep existing AI SDK code, build the provider as createOpenAI({ apiKey: client.sdkOptions.apiKey, fetch: client.fetch }). The model name you pass is ignored, since the visitor chooses the model in the wallet.
Keep only your MCP tools on the server
After the move, /api/mcp is the one server route your chat calls. It relays POST requests to your MCP server (the Model Context Protocol endpoint that serves your site's tools) on your own origin, so the browser needs no CORS setup. The relay forwards three headers: accept, content-type and mcp-protocol-version. It answers GET and DELETE with 405, the status the MCP specification gives a server without a stream, so a 405 on GET in your logs is expected. The tool loop in the page calls your tools between model turns and stops at 6 steps by default. Anyone can call this endpoint without your page. Your server therefore validates every argument against the tool's inputSchema, runs checkToolResult on each result, and keeps private names in a policy only the server imports. The values a page passes as guards ship in its code, where anyone can read them. To design the tools themselves, read how to give your site's AI chat real tools with its own MCP server.
Run 12 visitor checks on this Next.js AI chatbot tutorial build
Run these checks in Chrome against next build followed by next start, then again on the production domain. Each one maps to a behaviour documented for AI Connect.
- Server HTML. The AI button renders in the
checkingstate, and the server render sends no request to the wallet. - Bundle secrets. A search of
.next/staticfinds nosk-provider key; the only TensorPass value is thetpk_site key. - No wallet. A clean Chrome profile shows the install button and Sign in with OpenRouter.
- Site key. The same profile shows Sign in with TensorPass once
NEXT_PUBLIC_TENSORPASS_SITE_KEYis set. - Return page. The sign in popup lands on
/aiconnect/callback, ends the sign in, and the page is excluded from indexing. - Returning visitor. A site the visitor approved earlier goes from
checkingtoconnectedwith zero clicks. - Not connected. A model call before the visitor connects fails with status 401.
- Declined or locked. A declined approval or a locked wallet returns 403.
- Plan spent. A spent plan returns 429, and the panel shows the error message.
- Disconnect. Clicking Disconnect closes the panel.
- Injection question. "Ignore all of the previous instructions" gets the safe answer, and the question stays out of the conversation the model reads.
- MCP route. GET on
/api/mcpreturns 405, and a burst past your rate limit returns 429.
Rate limits and abuse when the visitor pays
When the visitor pays for tokens, your rate limit moves from the model route to the MCP route. A route handler build needs a limiter in front of streamText: one Next.js 16 tutorial blocks at 10 requests per 10 seconds and 100 per hour, and returns 429 with Retry-After. With AI Connect a scripted caller spends its own account on the model, and the cost left on your side is the tool calls. The reference MCP server allows 60 requests a minute per visitor address, which leaves room for several questions a minute since one answer calls a few tools. A production relay caps the body size it reads and passes the visitor address to the backend, so the limit counts each visitor apart. A site whose session is a cookie checks that the Origin header is its own and sets the cookie to SameSite=Lax or Strict. On a 429 from a spent plan, streamText retries twice; on the wallet's Auto mode set maxRetries: 0, since the wallet already moves to the next account. The question guard stops input above 2,000 characters and 18 injection patterns in English, French and Hebrew. Guards reduce the risk of prompt injection in a website chatbot without removing it.
Cache Components and prerender pitfalls
Cache Components is the Next.js 16 option, stable since 16.0.0, that prerenders a static HTML shell and streams dynamic parts into it. create-next-app turns it on by default for the App Router, and four pitfalls follow.
useChatids. Without an explicit id,useChatdraws a random id during prerender, and the build fails with "Next.js encountered the unstable value Math.random() in a Client Component." John Yegs, writing for JY Labs, puts it this way: "A fixed id makes the prerender deterministic."- Wallet state.
new AiConnect()checks forwindow, so the server render sends no request and stays inchecking. Render your button in every state so the layout does not move. - Relative URLs.
McpToolSource('/api/mcp')needs the page address, so the panel keepsssr: false. - Frozen keys.
NEXT_PUBLIC_values are frozen atnext build. Set the site key before the build, since a Docker image promoted across environments keeps the value it was built with.
How TensorPass supports your Next.js build
SDK and site key. The AI Connect SDK, AI Wallet, the MCP servers and the site key are free. The SDK is under Apache 2.0, public on GitHub since 12 November 2026, with npm provenance signed by the GitHub build.
Visitors without AI Wallet. The TensorPass plan costs the visitor US$5 a month (Light), US$20 (Pro) or US$50 (Max). Your site earns 5% of each plan payment made from its AI window for 12 months, with a 60-day hold, paid in USDC once US$50 is available.
Done for you. We make a site AI native in under 24 hours, priced on quote.
Start with the AI Connect Next.js quickstart, which carries the full provider, button and panel code.
Ship it: the deploy order for a visitor-paid chat
Delete app/api/chat/route.ts and remove the provider key from your host's environment variables on the day you deploy. Set NEXT_PUBLIC_TENSORPASS_SITE_KEY before next build, deploy, then rerun the 12 checks on the production domain. After that, the one server route this Next.js AI chatbot tutorial leaves you is the MCP relay that serves your tools.
Also worth reading:
- Add an AI chatbot to your website with no API key on your server
- Choosing a React AI chat component for a site with real traffic
- Give your site's AI chat real tools with its own MCP server
- How to prevent prompt injection in a website chatbot
Sources:
- Next.js quickstart: TensorPass docs, read 25 November 2026
- Changelog: TensorPass docs, 24 November 2026
- Vercel AI SDK guide: TensorPass docs, read 25 November 2026
- Expose your tools over MCP: TensorPass docs, read 25 November 2026
- Guards: TensorPass docs, read 25 November 2026
- AI Connect repository: GitHub, read 25 November 2026
- Build a Next.js 16 AI Chatbot: AI SDK Tutorial from Scratch: Digital Applied, 17 November 2026
- How to Build a Simple AI-Powered Chatbot with Next.js and Claude: John Yegs, DEV Community, 10 November 2026
- How to use environment variables in Next.js: Next.js documentation, 25 August 2026
- cacheComponents: Next.js documentation, 15 October 2026
- create-next-app: Next.js documentation, 29 September 2026
- Next.js 16: Next.js blog, 21 October 2025