Next.js integration
The main AI SDK chat path sits on Next.js App Router: app/api/chat/route.ts calls streamText, and a 'use client' page uses useChat. There is a separate official quickstart for the Pages Router; new apps should use the App Router.
Component rules: React tutorial. Types: TypeScript.
Suggested layout
Do not import { streamText } in page.tsx and expect the browser to call the model. That leaks logic and keys to the client.
Route handler checklist
If you need auth, read the cookie / session in the handler before calling the model. Do not put user secrets in a hardcoded useChat header.
Environment variables
Next.js only inlines NEXT_PUBLIC_ vars into the browser bundle. AI keys must never use that prefix.
Local: .env.local. Vercel: Project Settings → Environment Variables. Restart pnpm dev or redeploy after changes.
UI or RSC?
Official templates (Chatbot Starter, Multi-Modal Chat) follow the UI path. Copy those, not the RSC samples, unless you need generative UI.
Deploy checklist
- Production env vars match local (Gateway or OpenAI key).
maxDurationcovers worst-case latency.- Auth and rate-limit
/api/chat(there is an official rate-limiting template). - Do not log full
messages(user privacy). - Put the model string in an env var so you can switch models without a code-only release.
Pages Router uses pipeUIMessageStreamToResponse against a Node response; follow the official Pages Router quickstart for details.
HarnessAgent on Next.js (brief)
If the route runs HarnessAgent instead of streamText, the session lives in the harness. Resume by chat id; do not replay the full UI history into generate. You can still toUIMessageStream into useChat. See the official Harnesses UI guide for the full pattern.