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

app/
├── api/chat/route.ts    # POST; secrets live only here
├── page.tsx             # 'use client' + useChat
├── layout.tsx
└── actions.tsx          # only if you use experimental streamUI
.env.local               # AI_GATEWAY_API_KEY, gitignored

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

import {
  convertToModelMessages,
  createUIMessageStreamResponse,
  streamText,
  toUIMessageStream,
  type UIMessage,
} from 'ai';

export const maxDuration = 30;

export async function POST(req: Request) {
  const { messages }: { messages: UIMessage[] } = await req.json();

  const result = streamText({
    model: 'openai/gpt-4.1-mini',
    messages: await convertToModelMessages(messages),
    onError({ error }) {
      console.error(error);
    },
  });

  return createUIMessageStreamResponse({
    stream: toUIMessageStream({ stream: result.stream }),
  });
}
PointWhy it matters
maxDurationExtends the streaming limit on Vercel (seconds). Hobby plans cap this—check the platform docs.
convertToModelMessagesMust be awaited
Edge vs NodeStreaming + tools default to the Node runtime; do not flip Edge on just to “go faster” and lose Node APIs
ErrorsstreamText does not throw out of the route; use onError and the UI error state

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.

VariableUse
AI_GATEWAY_API_KEYDefault Gateway
OPENAI_API_KEY@ai-sdk/openai
Custom baseURLServer-only createOpenAI / createOpenAICompatible

Local: .env.local. Vercel: Project Settings → Environment Variables. Restart pnpm dev or redeploy after changes.


UI or RSC?

NeedChoose
Streaming chat, tools, productionAI SDK UI + the route handler in this chapter
Model emits React componentsExperimental @ai-sdk/rsc / streamUI (see RSC)
Headless batch workgenerateText in a route, Server Action, or pnpm script

Official templates (Chatbot Starter, Multi-Modal Chat) follow the UI path. Copy those, not the RSC samples, unless you need generative UI.


Deploy checklist

  1. Production env vars match local (Gateway or OpenAI key).
  2. maxDuration covers worst-case latency.
  3. Auth and rate-limit /api/chat (there is an official rate-limiting template).
  4. Do not log full messages (user privacy).
  5. 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.


Next

评论