Vercel AI SDK Tutorial: Build Next.js AI Apps

Updated 3 min read

Many developers struggle with outdated guides that rely on deprecated APIs like streamUI or obsolete streaming helpers. This vercel ai sdk tutorial shows you how to build a full-stack streaming chat interface and agent with tool calling in the Next.js App Router. By the end, you will have a working streaming application built on modern package boundaries.

Watch the video on YouTube

Before you start

  • Node.js 22 or later installed
  • Basic knowledge of Next.js App Router and React
  • An OpenAI API key

Project Setup and Dependencies

Start by creating a new Next.js application using the App Router and TypeScript. Modern releases of the AI SDK require Node.js 22 or later and native ECMAScript modules.

Run the project scaffolding commands below to generate your application directory without interactive prompts. Once inside the folder, install the server runtime, the dedicated React UI package, the model provider, and Zod for schema validation.

TerminalNot verified in our test run
node -v
npx --yes create-next-app@latest ai-chat --typescript --tailwind --eslint --app --src-dir --import-alias "@/*" --use-npm --skip-install
cd ai-chat && npm install ai @ai-sdk/react @ai-sdk/openai zod
Output from our test run
$ node -v
v22.23.3
$ npx --yes create-next-app@latest ai-chat --typescript --tailwind --eslint --app --src-dir --import-alias "@/*"
 --use-npm --skip-install

Using defaults for unprovided options:

  --ts                    TypeScript (use --js for JavaScript)
  --no-react-compiler     No React Compiler (use --react-compiler for React Compiler)
  --agents-md             AGENTS.md (use --no-agents-md for No AGENTS.md)

Creating a new Next.js app in /root/ai-chat.

Using npm.

Initializing project with template: app-tw

Initialized a git repository.

Success! Created ai-chat at /root/ai-chat

npm notice
npm notice New major version of npm available! 10.9.9 -> 12.2.0
npm notice Changelog: https://github.com/npm/cli/releases/tag/v12.2.0
npm notice To update run: npm install -g [email protected]
npm notice
$ cd ai-chat && npm install ai @ai-sdk/react @ai-sdk/openai zod

Architecture: Core, UI, and Providers

The modern architecture separates functionality across three distinct packages. The core package executes on the server to handle text generation, streaming pipelines, and tool execution.

The client hook package manages UI concerns like message history, input tracking, and automatic scrolling. Provider adapters connect these operations to upstream APIs without polluting client bundles.

Creating the Streaming Route Handler

Create an App Router POST route handler in the API path shown below to process messages from the frontend. The handler receives incoming messages from the request body and passes them into the text streaming helper.

Connect the stream to your chosen model provider and return a data stream response. This specialized response formats text tokens, execution metadata, and tool statuses into server-sent events that client hooks can consume.

src/app/api/chat/route.ts
import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';

export const maxDuration = 30;

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

  const result = streamText({
    model: openai('gpt-4o-mini'),
    system: 'You are a helpful, concise technical assistant.',
    messages,
  });

  return result.toDataStreamResponse();
}

Building the Chat Interface

Construct the main chat view as a client component using the standard chat hook. The hook defaults to your API chat route and manages state transitions, user input changes, and loading indicators automatically.

Render the conversation history by iterating over the message list and wire the input form directly to the submission handler. This pattern eliminates the need for manual network calls or complex reducer logic.

src/app/page.tsx
'use client';

import { useChat } from '@ai-sdk/react';

export default function ChatPage() {
  const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat();

  return (
    <main className="flex flex-col w-full max-w-md py-12 mx-auto stretch px-4">
      <header className="mb-6">
        <h1 className="text-xl font-bold">AI Assistant</h1>
      </header>

      <div className="space-y-4 mb-24">
        {messages.map((m) => (
          <div key={m.id} className="whitespace-pre-wrap text-sm">
            <span className="font-semibold">{m.role === 'user' ? 'You: ' : 'AI: '}</span>
            {m.content}
          </div>
        ))} {isLoading && <div className="text-sm text-gray-500">Thinking...</div>}
      </div>

      <form onSubmit={handleSubmit} className="fixed bottom-0 w-full max-w-md pb-6 bg-white">
        <input
          className="w-full p-2 border border-gray-300 rounded shadow-sm"
          value={input}
          placeholder="Ask a question..."
          onChange={handleInputChange}
        />
      </form>
    </main>
  );
}

Adding Tools and Multi-Step Execution

Expand the server route handler into an agent by supplying executable tools with Zod schema definitions. When the model requests external data, it triggers your function and awaits the structured output.

Configure the maximum steps parameter to ensure the tool call completes its loop. Without this setting, the stream terminates after calling the tool instead of feeding the result back into the model for a final response.

src/app/api/chat/route.ts
import { openai } from '@ai-sdk/openai';
import { streamText, tool } from 'ai';
import { z } from 'zod';

export const maxDuration = 30;

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

  const result = streamText({
    model: openai('gpt-4o-mini'),
    system: 'You are a helpful assistant with access to tools.',
    messages,
    maxSteps: 5,
    tools: {
      getTemperature: tool({
        description: 'Get current temperature for a city in Celsius',
        parameters: z.object({
          city: z.string().describe('The name of the city'),
        }),
        execute: async ({ city }) => {
          return { city, temperature: 21, condition: 'Sunny' };
        },
      }),
    },
  });

  return result.toDataStreamResponse();
}

Rendering Tool Invocations on the Client

Rather than relying on deprecated server component streaming methods, inspect the tool invocations array directly on client message objects. Each entry tracks whether a tool call is actively executing or has returned data.

Conditionally render components such as badges, cards, or status blocks based on whether the invocation contains a result. This keeps generative interface elements deterministic and isolated within standard React components.

src/app/page.tsx
{m.toolInvocations?.map((tool) => (
  <div key={tool.toolCallId} className="my-2 p-3 bg-gray-50 border rounded text-xs font-mono">
    <div className="font-bold text-gray-700">Tool: {tool.toolName}</div>
    {'result' in tool ? (
      <div className="text-green-700 mt-1">
        Result: {JSON.stringify(tool.result)}
      </div>
    ) : (
      <div className="text-amber-600 mt-1">Executing tool...</div>
    )}
  </div>
))}

Verifying the Next.js Build

Validate your application by executing the project build script. This step compiles both the client pages and API routes while checking TypeScript typings across your schemas and hook integrations.

When preparing for deployment, configure your model API key inside your hosting provider environment variables to ensure server routes can reach external APIs securely.

TerminalNot verified in our test run
# Verify complete build and TypeScript compilation
npm run build
Output from our test run
$ npm run build

> [email protected] build
> next build

▲ Next.js 16.3.8 (Turbopack)
✓ Running next.config.ts took 89ms
Attention: Next.js now collects completely anonymous telemetry regarding usage.
This information is used to shape Next.js' roadmap and prioritize features.
You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visi
ting the following URL:
https://nextjs.org/telemetry

  Creating an optimized production build ...
✓ Compiled successfully in 9.8s
✓ Finished TypeScript in 4.1s
✓ Collecting page data using 5 workers in 961ms
✓ Generating static pages using 5 workers (4/4) in 1100ms
✓ Finalizing page optimization in 19ms

Route (app)
┌ ○ /
└ ○ /_not-found

○  (Static)  prerendered as static content

Wrap-up

You now have a clean, reproducible setup for building streaming chat apps and multi-step agents using the modern Vercel AI SDK and Next.js App Router. By respecting the boundary between server execution and client hooks, your AI workflows remain maintainable and fast.

FAQ

Why should I not import useChat from the core ai package?

Modern SDK architecture separates server-side execution into the core package and client-side hooks into a dedicated React package. Importing hooks from the wrong path breaks bundle boundaries and references outdated APIs.

Why does my agent stop talking after executing a tool?

Text streaming stops after executing a tool call by default. You must configure the maximum steps option on the stream text call so the model can process the tool result and generate a follow-up answer.

How does generative UI work without streamUI?

Instead of experimental server component streaming, modern interfaces inspect tool invocations directly within client message objects and render standard React components based on execution state.

Sources

Subscribe for more tested tutorials