TensorPass

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 @tensorpass scope 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 at next build, so the one key left in your environment is the public site key (tpk_...).
  • create-next-app enables Cache Components by default for App Router projects, and a useChat call without a fixed id fails that prerender on Math.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 buildAI Connect build
Model call runs inapp/api/chat/route.ts on your serverA client component in the visitor's browser
Secret in .env.localProvider key (sk-ant-...)None; the site key tpk_... is public
Account billed per answerYour provider accountThe visitor's AI account
Server route leftChat route and its rate limiterMCP relay at /api/mcp
Model choiceYou pin it in codeThe 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-react

The 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.

A single server route linked by one cable to a laptop, the MCP relay left after the chat route goes away

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.

  1. Server HTML. The AI button renders in the checking state, and the server render sends no request to the wallet.
  2. Bundle secrets. A search of .next/static finds no sk- provider key; the only TensorPass value is the tpk_ site key.
  3. No wallet. A clean Chrome profile shows the install button and Sign in with OpenRouter.
  4. Site key. The same profile shows Sign in with TensorPass once NEXT_PUBLIC_TENSORPASS_SITE_KEY is set.
  5. Return page. The sign in popup lands on /aiconnect/callback, ends the sign in, and the page is excluded from indexing.
  6. Returning visitor. A site the visitor approved earlier goes from checking to connected with zero clicks.
  7. Not connected. A model call before the visitor connects fails with status 401.
  8. Declined or locked. A declined approval or a locked wallet returns 403.
  9. Plan spent. A spent plan returns 429, and the panel shows the error message.
  10. Disconnect. Clicking Disconnect closes the panel.
  11. Injection question. "Ignore all of the previous instructions" gets the safe answer, and the question stays out of the conversation the model reads.
  12. MCP route. GET on /api/mcp returns 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.

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:

Sources:

Read the quickstartRead the changelog