Vercel AI SDK Tutorial: Build a Streaming Chat App With Next.js
Build a streaming chat app with the Vercel AI SDK and Next.js: a streamText route handler plus the useChat hook. Two files, live token-by-token replies.
By Galactic News Editorial · Published 2026-11-18T10:33:22+00:00 · Updated 2026-11-18T10:33:22+00:00
This Vercel AI SDK tutorial builds a streaming chat app with Next.js. You will create an API route that streams tokens from a language model, and a client component that renders them live with the useChat hook. Two files carry the whole feature. By the end, a message you send will appear word by word instead of arriving in one block.
Vercel AI SDK tutorial: what the SDK is
The Vercel AI SDK is an open-source TypeScript toolkit for building AI features. It has two layers. AI SDK Core gives you provider-agnostic functions like generateText, streamText, and generateObject. The same call works with OpenAI, Anthropic, Google, or another provider. You switch models by changing the provider package and the model id. AI SDK UI adds framework hooks like useChat that consume streamed responses in the browser.
Streaming is the point. A blocking response makes the user wait for the full answer. A 500-token reply can take eight to fifteen seconds. With streaming, the first token arrives in roughly 200 to 300 milliseconds and the text renders as it arrives. The SDK owns the plumbing: the server produces the stream, the client consumes it, and the protocol carries text, tool calls, and finish events over a single HTTP response.
Use the current major version. AI SDK 7 was released in June 2026 and is ESM-only, so require() will not work. The useChat hook comes from @ai-sdk/react, not from the removed ai/react path. Older tutorials show removed helpers like StreamingTextResponse and toAIStream. Check the docs for your installed major version before copying any example.
Step 1: Create the Next.js app
Create a fresh App Router project. AI SDK 7 needs Node.js 22 or newer, because the ai package enforces it in its engines field. Accept App Router and Tailwind when the installer asks.
pnpm create next-app@latest my-ai-app
cd my-ai-app
Step 2: Install the SDK and a provider
Install the core package, the React hooks package, and one provider. Zod is useful later for structured output and tool inputs.
pnpm add ai @ai-sdk/react @ai-sdk/openai zod
If you call Anthropic instead of OpenAI, install @ai-sdk/anthropic and skip @ai-sdk/openai. The rest of the code stays the same. That is the benefit of the provider-agnostic design.
Step 3: Add your API key
Create a .env.local file in the project root. Keep the key on the server. Never ship a provider key to the browser.
OPENAI_API_KEY=sk-your-key-here
The OpenAI provider reads this variable by default. Restart the dev server after you add the file.
Step 4: Build the API route with streamText
Create app/api/chat/route.ts. The handler reads the messages from the request, calls streamText, and returns a UI message stream response. Export maxDuration so the serverless function lives long enough to finish streaming.
import { openai } from '@ai-sdk/openai';
import { streamText, createUIMessageStreamResponse, convertToModelMessages, toUIMessageStream } from 'ai';
export const maxDuration = 30;
export async function POST(req: Request) {
const { messages } = await req.json();
const result = streamText({
model: openai('gpt-4o'),
messages: await convertToModelMessages(messages),
});
return createUIMessageStreamResponse({
stream: toUIMessageStream(result),
});
}
streamText returns a result object at once. It does not block on the full generation. The response helper turns that result into a streaming HTTP response the useChat hook understands. Keep the handler small. Rate limiting, auth, and logging belong here too, before the model call.
Step 5: Build the chat UI with useChat
Replace app/page.tsx with a client component. useChat manages the message array and the fetch to /api/chat. It defaults to POST /api/chat, so no fetch code is needed. Hold the input in your own useState. Render each message from its parts array, not from a single content string. Switch on part.type so text, tool calls, and reasoning each render in order.
'use client';
import { useChat } from '@ai-sdk/react';
import { useState } from 'react';
export default function Chat() {
const [input, setInput] = useState('');
const { messages, sendMessage, status } = useChat();
return (
<div>
{messages.map(message => (
<div key={message.id}>
<strong>{message.role}:</strong>
{message.parts.map((part, i) =>
part.type === 'text' ? <span key={i}>{part.text}</span> : null
)}
</div>
))}
<form onSubmit={e => {
e.preventDefault();
sendMessage({ text: input });
setInput('');
}}>
<input value={input} onChange={e => setInput(e.target.value)} />
<button disabled={status !== 'ready'}>Send</button>
</form>
</div>
);
}
The status field has four states: submitted, streaming, ready, and error. Disable the send button while status is not ready. That stops double submissions while a reply is still streaming.
Step 6: Run it and watch the stream
Start the dev server and open the app. Send a message. The reply should grow word by word. If nothing streams, check three things. First, the route file exports a POST function. Second, the API key is set and the dev server was restarted after you added it. Third, the client imports useChat from @ai-sdk/react. An import from ai/react will fail on current versions.
pnpm run dev
Production checklist
A working demo is not a production app. Add these before you ship. Rate limit /api/chat, for example ten requests per minute per IP. An open chat URL without limits is someone else's free API. Add auth if the chat is not public. Handle errors in the UI: show a retry button when status becomes error. Cap the conversation length you send to the model, or costs grow with every turn. Log token usage per request so a spike is visible. Finally, pin your SDK versions and read the migration guide before upgrading a major version. The API names moved between v4, v5, and v7, and old snippets are the most common source of code that will not compile.
Bottom line
A streaming chat app with the Vercel AI SDK is two files: a route handler that calls streamText and returns a UI message stream, and a client component that renders message parts with useChat. Install ai, @ai-sdk/react, and a provider package. Keep the key on the server. Render from message.parts, respect the status field, and rate limit the route before you ship. That foundation carries tool calling, structured output, and multi-step agents later too.