Development4 min read

Vercel AI SDK 6: Streaming AI Chat with Next.js

Build streaming chat with AI SDK 6, Next.js Route Handlers and useChat. Add structured output, validate requests, and keep model and tool access server-side.

Published · Updated
4 min read
Route Handler

Chat endpoint

useChat

Client hook

Output.object

Structured data

Key Takeaways

Pair matching stream protocols: Use useChat with a route that returns a UI message stream response.
Separate model and UI messages: Validate incoming messages and convert them to the model format before generation.
Authorize tools on the server: A declared input schema validates arguments. The application still decides which actions a user may perform.

AI SDK 6 supports streamed chat interfaces on Next.js. The server invokes the model, while the React client renders the parts of each incoming message.

This example uses a Route Handler for the chat transport. It also shows where structured data and tools enter the server-side workflow.

The code below pairs a server route with a matching client. Before deployment, exercise invalid messages, provider failures and authorization checks in your own environment.

Related guidance: AI integration services.

What changed in AI SDK 6

Vercel’s release highlighted reusable agents, tool execution approval and structured output alongside normal text generation. The core text functions and UI chat transport still work together. Vercel’s AI SDK 6 announcement.

Server Actions are an application option. The RSC package is experimental, and its streaming primitives differ from the HTTP transport used below. AI SDK RSC documentation.

Install the SDK 6 packages

For this historical example, keep the core and React packages on compatible major versions. Install a provider integration that supports the chosen model. Store the API key only in the server environment and set CHAT_MODEL to a supported model ID from that provider.

npm install ai@6 @ai-sdk/react@3 @ai-sdk/openai@3 zod

Stream UI messages from a Next.js route

The hook sends UI messages to /api/chat by default. This minimal route validates their shape, converts them to model messages and returns the stream protocol expected by the UI. Add authentication, account limits and request-size limits before making the route public. the AI SDK 6 chatbot guide.

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

export async function POST(request: Request) {
  const modelId = process.env.CHAT_MODEL;
  if (!modelId) return new Response('Model unavailable', { status: 503 });
  const body = await request.json().catch(() => null);
  if (!Array.isArray(body?.messages)) return new Response('Invalid messages', { status: 400 });
  const messages = await validateUIMessages({ messages: body.messages }).catch(() => null);
  if (!messages) return new Response('Invalid messages', { status: 400 });
  const result = streamText({
    model: openai(modelId),
    messages: await convertToModelMessages(messages),
    abortSignal: request.signal,
  });
  return result.toUIMessageStreamResponse();
}
// app/chat/page.tsx
'use client';
import { useChat } from '@ai-sdk/react';
import { useState } from 'react';

export default function Chat() {
  const { messages, sendMessage, status, error } = useChat();
  const [text, setText] = useState('');
  return <main>
    {messages.map(m => <p key={m.id}>{m.parts.map((p, i) =>
      p.type === 'text' ? <span key={i}>{p.text}</span> : null)}</p>)}
    {error && <p role="alert">The response could not be completed.</p>}
    <form onSubmit={e => { e.preventDefault(); if (text.trim()) {
      void sendMessage({ text }); setText('');
    } }}>
      <input aria-label="Message" value={text} onChange={e => setText(e.target.value)} />
      <button disabled={status !== 'ready' || !text.trim()}>Send</button>
    </form>
  </main>;
}

Generate a structured response

Use the output option on a text generation call. Have a separate application path for an unsupported schema, provider error or response that cannot be parsed. the structured data guide.

import { generateText, Output } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';

export async function classifyFeedback(modelId: string, feedback: string) {
  const { output } = await generateText({
    model: openai(modelId),
    output: Output.object({ schema: z.object({ category: z.enum(['bug', 'request', 'other']) }) }),
    prompt: feedback,
  });
  return output.category;
}

Validate and authorize tool calls

Use tool definitions with inputSchema and an execute handler for server-side functions. Derive account and tenant identity from the authenticated request. A model-proposed account ID cannot grant access.

Check permission and request user approval before consequential actions. Store an idempotency key for a write so a repeated tool call cannot charge or reserve the same item twice.

Compare providers on the same task

The provider adapter supplies the model to the text-generation call. Tool support, structured output, context windows, model availability and pricing vary by provider and deployment.

Choose a fixed set of representative inputs, measure successful completions and total tokens, and include retries and human review in the cost. Run the same evaluation after changing model or adapter versions.

Limit usage and handle interrupted streams

Enforce the session, tenant boundary, maximum input size and a per-account usage budget before generation. The sample route illustrates message transport only. Treat client-supplied roles, prior assistant messages and tool results as untrusted. A durable conversation should load its trusted history on the server.

Handle failures before a stream starts with an HTTP status. Once bytes have been sent, model errors need the stream protocol’s error path. Expose a short user-facing error and retain request identifiers for diagnostics.

Verify the deployed streaming path

Check the actual deployment’s function duration, region, provider credentials and streaming behavior with a slow request. Test client cancellation and provider timeouts at the deployed URL.

A stream that renders progressively does not establish that the assistant turn was saved. For durable history, attach the turn to its owner and persist completed or interrupted outcomes explicitly.

Build AI-Powered Applications

Our team builds production-ready AI features with Next.js and the Vercel AI SDK — from streaming chat interfaces to intelligent automation workflows.

Free consultation
Expert guidance
Tailored solutions

Frequently Asked Questions

Corrections

Correction, : Replaced the deprecated streamText and useChat examples and unsupported claim that v6 requires Server Actions. Corrected structured output, model routing, billing and deployment guidance.

Digital Applied newsletter

Deep dives on AI, marketing and development.

Practical guides and fresh insights by email. No recycled takes.

Related Guides

Continue exploring these insights and strategies.