---
title: "Vercel AI SDK 7 Tutorial for Next.js and Nuxt (2026)"
description: "A hands-on Vercel AI SDK 7 tutorial with streaming chat in useChat, tools, generative UI and approvals in Next.js and Nuxt, plus a production checklist."
canonical_url: "https://liviu.dev/blog/12/vercel-ai-sdk-tutorial-nextjs-nuxt"
---

> Index of every page on this site: [llms.txt](https://liviu.dev/llms.txt)

The Vercel AI SDK is the TypeScript library most React and Vue teams reach for when they add a chat, an assistant or an agent to a product. Version 7 shipped on 25 June 2026 and renamed a good part of the API, so many tutorials written for version 5 or 6 no longer compile.

I build Nuxt and React front ends with AI features, so for this guide I built the same order-support assistant twice, in Next.js and in Nuxt 4. It streams answers, looks orders up with a tool, renders the result as a card and asks before it cancels anything. Every snippet was type-checked against `ai` 7.0.173, the current release at the time of writing, with `@ai-sdk/react` 4.0.177 and `@ai-sdk/vue` 4.0.173. I also ran both route handlers against the SDK's mock model, so the tool calls and approvals below behave as described.

## What is the Vercel AI SDK?

The AI SDK is a free, open-source TypeScript toolkit from Vercel for building AI features and agents with any model provider. Its core calls models (text, structured output, tools, streaming), and its UI packages give React, Vue, Svelte and Angular a `useChat` hook that renders the streamed reply.

The key facts:

- **Who makes it.** Vercel. The source is at [github.com/vercel/ai](https://github.com/vercel/ai) under the Apache-2.0 licence, and the docs live at [ai-sdk.dev](https://ai-sdk.dev).
- **Status.** Stable, version 7, released on 25 June 2026. Vercel put it at over 16 million weekly downloads when 7 shipped.
- **Requirements.** Node.js 22 or newer, and ESM, since version 7 dropped CommonJS.
- **Providers.** OpenAI, Anthropic, Google and dozens more through provider packages. The Vercel AI Gateway provider ships inside `ai`, so a plain string such as `"anthropic/claude-sonnet-5.5"` works with one gateway key.

<table>
<thead>
  <tr>
    <th>
      Package
    </th>
    
    <th>
      What it does
    </th>
    
    <th>
      Used in this guide
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        ai
      </code>
    </td>
    
    <td>
      AI SDK Core, with <code>
        streamText
      </code>
      
      , <code>
        generateText
      </code>
      
      , tools, agents, UI message streams and the AI Gateway provider
    </td>
    
    <td>
      Both apps
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        @ai-sdk/react
      </code>
    </td>
    
    <td>
      AI SDK UI for React and Next.js, with <code>
        useChat
      </code>
      
      , <code>
        useCompletion
      </code>
      
       and <code>
        useObject
      </code>
    </td>
    
    <td>
      Next.js
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        @ai-sdk/vue
      </code>
    </td>
    
    <td>
      The same hooks as Vue composables
    </td>
    
    <td>
      Nuxt
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        @ai-sdk/svelte
      </code>
      
      , <code>
        @ai-sdk/angular
      </code>
    </td>
    
    <td>
      The same for Svelte and Angular
    </td>
    
    <td>
      No
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        @ai-sdk/openai
      </code>
      
      , <code>
        @ai-sdk/anthropic
      </code>
      
       and others
    </td>
    
    <td>
      Direct access to one provider, without the gateway
    </td>
    
    <td>
      Optional
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        zod
      </code>
    </td>
    
    <td>
      Schemas for tool inputs
    </td>
    
    <td>
      Both apps
    </td>
  </tr>
</tbody>
</table>

Vercel also has a newer, unrelated library with a similar name, UI SDK, which builds accessible components and lets agents operate them. I covered it in [Vercel UI SDK Setup Guide for Next.js and Nuxt](https://liviu.dev/blog/11/vercel-ui-sdk-setup-guide-nextjs-nuxt). This post is about the AI SDK, the one that talks to models.

## What's new in AI SDK 7?

AI SDK 7 is about running agents in production, with approvals, typed context, timeouts, durable runs and telemetry. It also renamed common options, which is why older tutorials break.

What it added:

- **One reasoning option** on `generateText` and `streamText`, from `"none"` to `"max"`, mapped to each provider's own reasoning setting.
- **Typed tool context.** A tool declares `contextSchema`, and you pass its values per tool in `toolsContext`. I use it below to hand tools the signed-in user's ID.
- **Tool approvals** with `toolApproval` on `generateText`, `streamText` and `ToolLoopAgent`. You can always ask, decide per call with a function, or approve and deny automatically. Approvals can be HMAC-signed so a client can't forge one.
- **Durable agents.** `WorkflowAgent` in `@ai-sdk/workflow` survives restarts, deploys and slow approvals.
- **Timeouts** for the whole call, each step, each chunk and each tool, which abort with a `TimeoutError`.
- **Telemetry** with `registerTelemetry` and integrations such as `@ai-sdk/otel`.
- **More, mostly experimental.** MCP Apps, a `HarnessAgent` that runs harnesses such as Claude Code and Codex, sandbox sessions, a terminal UI, voice and video.

If you're upgrading from version 6, these are the renames you'll hit first:

<table>
<thead>
  <tr>
    <th>
      AI SDK 6
    </th>
    
    <th>
      AI SDK 7
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        system: "…"
      </code>
    </td>
    
    <td>
      <code>
        instructions: "…"
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        stopWhen: stepCountIs(5)
      </code>
    </td>
    
    <td>
      <code>
        stopWhen: isStepCount(5)
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        onFinish
      </code>
      
      , <code>
        onStepFinish
      </code>
    </td>
    
    <td>
      <code>
        onEnd
      </code>
      
      , <code>
        onStepEnd
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        result.fullStream
      </code>
    </td>
    
    <td>
      <code>
        result.stream
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        return result.toUIMessageStreamResponse()
      </code>
    </td>
    
    <td>
      <code>
        return createUIMessageStreamResponse({ stream: toUIMessageStream({ stream: result.stream }) })
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        needsApproval
      </code>
      
       on the tool
    </td>
    
    <td>
      <code>
        toolApproval
      </code>
      
       on the call
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        experimental_context
      </code>
    </td>
    
    <td>
      <code>
        context
      </code>
      
      , filled from <code>
        toolsContext
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        new Chat()
      </code>
      
       from <code>
        @ai-sdk/vue
      </code>
    </td>
    
    <td>
      <code>
        useChat()
      </code>
      
       from <code>
        @ai-sdk/vue
      </code>
    </td>
  </tr>
</tbody>
</table>

Some old names, such as `system`, `onFinish`, `toUIMessageStreamResponse()` and Vue's `Chat` class, still work as deprecated aliases. One change can break a working app, though. System messages inside `messages` are now rejected unless you set `allowSystemInMessages: true`. The codemod handles most of the renames:

```bash
npx @ai-sdk/codemod v7
```

## How does useChat work?

`useChat` keeps the conversation as an array of UI messages in the browser. On each send, it posts the whole history to `/api/chat` and renders the streamed reply as typed parts.

1. **sendMessage({ text })** adds the user's message and posts all messages to `/api/chat`.
2. **The route handler** turns them into model messages with `convertToModelMessages`, calls `streamText`, and streams the result back with `toUIMessageStream` and `createUIMessageStreamResponse`.
3. **The hook appends parts** to the assistant's message as they arrive, and `status` moves from `submitted` to `streaming` to `ready` (or `error`).
4. **You render message.parts** in order, one branch per part type.

<table>
<thead>
  <tr>
    <th>
      Part type
    </th>
    
    <th>
      What it holds
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        text
      </code>
    </td>
    
    <td>
      The model's text, streamed in
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        reasoning
      </code>
    </td>
    
    <td>
      Reasoning tokens, when the model sends them
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        tool-<name>
      </code>
    </td>
    
    <td>
      One call of a tool you defined, such as <code>
        tool-getOrder
      </code>
      
      , with its input, state and output
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        dynamic-tool
      </code>
    </td>
    
    <td>
      A tool unknown at compile time, such as one loaded from an MCP server
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        data-<name>
      </code>
    </td>
    
    <td>
      Custom data you stream from the server
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        source-url
      </code>
      
      , <code>
        file
      </code>
    </td>
    
    <td>
      Sources and files the model returns
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        step-start
      </code>
    </td>
    
    <td>
      The boundary between two steps of a multi-step call
    </td>
  </tr>
</tbody>
</table>

Because the client sends the full history every time, the server has to treat it as untrusted input. I come back to that in the checklist.

## How to set up the AI SDK in Next.js

You install three packages, add an AI Gateway key, write one route handler and one client component. These steps follow the official App Router quickstart.

### 1. Create the app and install the packages

You need Node.js 22 or newer.

```bash
pnpm create next-app@latest my-ai-app
cd my-ai-app
pnpm add ai @ai-sdk/react zod
```

### 2. Add your AI Gateway key

Create an API key in the AI Gateway section of your Vercel dashboard and put it in `.env.local`:

```bash
# .env.local
AI_GATEWAY_API_KEY=your-key
```

The gateway provider reads `AI_GATEWAY_API_KEY` on its own, so model strings such as `"anthropic/claude-sonnet-5.5"` just work. To call a provider directly instead, install its package (for example `@ai-sdk/openai`) and pass its model in place of the string.

### 3. Create the route handler

```ts
// app/api/chat/route.ts
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: "anthropic/claude-sonnet-5.5",
    instructions: "You are the support assistant of an online shop. Keep answers short.",
    messages: await convertToModelMessages(messages),
  })

  return createUIMessageStreamResponse({
    stream: toUIMessageStream({ stream: result.stream }),
  })
}
```

`instructions` is the system prompt (it was `system` before version 7). `maxDuration` lets the function stream for up to 30 seconds on Vercel.

### 4. Build the chat page

```tsx
// app/page.tsx
"use client"

import { useChat } from "@ai-sdk/react"
import { useState } from "react"

export default function ChatPage() {
  const [input, setInput] = useState("")
  const { messages, sendMessage, status, stop, error } = useChat()
  const busy = status === "submitted" || status === "streaming"

  return (
    <main className="mx-auto max-w-xl p-6">
      {messages.map((message) => (
        <div key={message.id} className="mb-4">
          <strong>{message.role === "user" ? "You" : "Assistant"}</strong>
          {message.parts.map((part, i) =>
            part.type === "text" ? <p key={i}>{part.text}</p> : null,
          )}
        </div>
      ))}

      {error && <p role="alert">Something went wrong. Please try again.</p>}

      <form
        onSubmit={(e) => {
          e.preventDefault()
          if (!input.trim()) return
          sendMessage({ text: input })
          setInput("")
        }}
      >
        <input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Ask about an order"
        />
        {busy ? (
          <button type="button" onClick={() => stop()}>Stop</button>
        ) : (
          <button type="submit">Send</button>
        )}
      </form>
    </main>
  )
}
```

`useChat` posts to `/api/chat` by default, so there's nothing to configure. The hook no longer manages the input for you, as it did before version 5, which is why the page keeps it in `useState`. Run `pnpm dev`, open `http://localhost:3000`, and the reply streams in word by word.

## How to add tools to an AI SDK chatbot

A tool is a function the model can decide to call. You define it with `tool()` (a description, a Zod input schema and an `execute` function), pass it to `streamText`, and set `stopWhen` so the model can answer after it sees the result.

### 1. Stand in for your database

The assistant needs orders to look up. In a real app, this is your database. For the tutorial, an in-memory map does:

```ts
// lib/orders.ts: an in-memory stand-in for your database
export type Order = {
  id: string
  status: "processing" | "shipped" | "delivered"
  total: string
  eta: string
}

const orders: Record<string, Order & { userId: string }> = {
  A1001: { id: "A1001", userId: "u_1", status: "processing", total: "€84.00", eta: "Thursday" },
}

export async function findOrder(userId: string, orderId: string): Promise<Order | undefined> {
  const order = orders[orderId]
  if (!order || order.userId !== userId) return undefined
  return { id: order.id, status: order.status, total: order.total, eta: order.eta }
}

export async function cancelOrder(userId: string, orderId: string): Promise<boolean> {
  const order = orders[orderId]
  if (!order || order.userId !== userId || order.status !== "processing") return false
  delete orders[orderId]
  return true
}
```

Both functions take the user's ID, so nobody reaches someone else's orders.

### 2. Define the tools

```ts
// lib/ai/tools.ts
import { tool, type InferUITools, type UIDataTypes, type UIMessage } from "ai"
import { z } from "zod"
import { cancelOrder, findOrder } from "@/lib/orders"

const userContext = z.object({ userId: z.string() })

export const tools = {
  getOrder: tool({
    description: "Look up an order by its number. The user sees the result as a card.",
    inputSchema: z.object({
      orderId: z.string().describe("The order number, for example A1001"),
    }),
    contextSchema: userContext,
    execute: async ({ orderId }, { context }) => {
      const order = await findOrder(context.userId, orderId)
      if (!order) throw new Error(`No order ${orderId} on this account.`)
      return order
    },
  }),
  cancelOrder: tool({
    description: "Cancel an order that hasn't shipped yet.",
    inputSchema: z.object({ orderId: z.string() }),
    contextSchema: userContext,
    execute: async ({ orderId }, { context }) => {
      const cancelled = await cancelOrder(context.userId, orderId)
      return { orderId, cancelled }
    },
  }),
}

export type ChatMessage = UIMessage<never, UIDataTypes, InferUITools<typeof tools>>
```

The model chooses `orderId`, but never `userId`. That arrives through `context`, which your server fills in, so a prompt like "show me order A1002" can't reach another customer's order.

`ChatMessage` is the message type with your tools in it. Pass it to `useChat`, and every tool part knows its input and output types.

### 3. Use the tools in the route handler

```ts
// app/api/chat/route.ts
import {
  convertToModelMessages,
  createUIMessageStreamResponse,
  isStepCount,
  streamText,
  toUIMessageStream,
  validateUIMessages,
} from "ai"
import { tools, type ChatMessage } from "@/lib/ai/tools"
import { getUserId } from "@/lib/auth"

export const maxDuration = 30

export async function POST(req: Request) {
  const userId = await getUserId(req)
  if (!userId) return new Response("Unauthorized", { status: 401 })

  const body = await req.json()
  const messages = await validateUIMessages<ChatMessage>({ messages: body.messages, tools })

  const result = streamText({
    model: "anthropic/claude-sonnet-5.5",
    instructions:
      "You are the support assistant of an online shop. Use the tools to look up and cancel orders. Keep answers short.",
    messages: await convertToModelMessages(messages),
    tools,
    toolsContext: {
      getOrder: { userId },
      cancelOrder: { userId },
    },
    toolApproval: { cancelOrder: "user-approval" },
    stopWhen: isStepCount(5),
  })

  return createUIMessageStreamResponse({
    stream: toUIMessageStream({ stream: result.stream }),
  })
}
```

What changed from the first version:

- **getUserId** stands for your auth (Auth.js, Clerk, Supabase or your own session). Without a user there is no chat.
- **validateUIMessages** checks the history the client sent, including every tool part, against your tools' schemas.
- **toolsContext** gives each tool the user's ID.
- **toolApproval** makes `cancelOrder` wait for the user. More on that below.
- **stopWhen: isStepCount(5)** lets the model call a tool, read the result and keep going, for up to five steps. Without it, the reply ends at the tool call and the user sees no answer.

## How to render generative UI from tool results

In AI SDK UI, generative UI means rendering your own components from tool parts. Each tool call reaches the client as a `tool-<name>` part, and you show something for each of its states, such as a spinner while it runs, a component when the output arrives and an error when it fails.

<table>
<thead>
  <tr>
    <th>
      State
    </th>
    
    <th>
      When
    </th>
    
    <th>
      What I render
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        input-streaming
      </code>
    </td>
    
    <td>
      The model is still writing the tool's input
    </td>
    
    <td>
      A placeholder
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        input-available
      </code>
    </td>
    
    <td>
      The input is complete and the tool is running
    </td>
    
    <td>
      "Looking up the order…"
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        approval-requested
      </code>
    </td>
    
    <td>
      The tool needs a person's approval first
    </td>
    
    <td>
      Approve and deny buttons
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        approval-responded
      </code>
    </td>
    
    <td>
      The person answered, the tool hasn't finished
    </td>
    
    <td>
      A short status
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        output-available
      </code>
    </td>
    
    <td>
      The tool returned
    </td>
    
    <td>
      The component, built from <code>
        part.output
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        output-error
      </code>
    </td>
    
    <td>
      The tool threw or its input was invalid
    </td>
    
    <td>
      <code>
        part.errorText
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        output-denied
      </code>
    </td>
    
    <td>
      The approval was refused
    </td>
    
    <td>
      "Order kept."
    </td>
  </tr>
</tbody>
</table>

The component is plain React. It knows nothing about AI:

```tsx
// components/order-card.tsx
import type { Order } from "@/lib/orders"

export function OrderCard({ order }: { order: Order }) {
  return (
    <article className="rounded-lg border p-4">
      <h3 className="font-semibold">Order {order.id}</h3>
      <p>{order.status === "delivered" ? "Delivered" : `Arrives ${order.eta}`}</p>
      <p>Total: {order.total}</p>
    </article>
  )
}
```

The page renders each part by its type and state:

```tsx
// app/page.tsx
"use client"

import { useChat } from "@ai-sdk/react"
import { lastAssistantMessageIsCompleteWithApprovalResponses } from "ai"
import { useState } from "react"
import { OrderCard } from "@/components/order-card"
import type { ChatMessage } from "@/lib/ai/tools"

export default function ChatPage() {
  const [input, setInput] = useState("")
  const { messages, sendMessage, addToolApprovalResponse, status, stop } = useChat<ChatMessage>({
    sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses,
  })
  const busy = status === "submitted" || status === "streaming"

  return (
    <main className="mx-auto max-w-xl p-6">
      {messages.map((message) => (
        <div key={message.id} className="mb-4">
          <strong>{message.role === "user" ? "You" : "Assistant"}</strong>
          {message.parts.map((part, i) => {
            const key = `${message.id}-${i}`

            switch (part.type) {
              case "text":
                return <p key={key}>{part.text}</p>

              case "tool-getOrder":
                if (part.state === "output-available") {
                  return <OrderCard key={key} order={part.output} />
                }
                if (part.state === "output-error") {
                  return <p key={key} role="alert">{part.errorText}</p>
                }
                return <p key={key}>Looking up the order…</p>

              case "tool-cancelOrder":
                if (part.state === "approval-requested") {
                  return (
                    <div key={key}>
                      <p>Cancel order {part.input.orderId}?</p>
                      <button onClick={() => addToolApprovalResponse({ id: part.approval.id, approved: true })}>
                        Cancel it
                      </button>
                      <button onClick={() => addToolApprovalResponse({ id: part.approval.id, approved: false })}>
                        Keep it
                      </button>
                    </div>
                  )
                }
                if (part.state === "output-available") {
                  return (
                    <p key={key}>
                      {part.output.cancelled
                        ? `Order ${part.output.orderId} is cancelled.`
                        : "That order can no longer be cancelled."}
                    </p>
                  )
                }
                if (part.state === "output-denied") return <p key={key}>Order kept.</p>
                return null

              default:
                return null
            }
          })}
        </div>
      ))}

      <form
        onSubmit={(e) => {
          e.preventDefault()
          if (!input.trim()) return
          sendMessage({ text: input })
          setInput("")
        }}
      >
        <input value={input} onChange={(e) => setInput(e.target.value)} placeholder="Ask about an order" />
        {busy ? (
          <button type="button" onClick={() => stop()}>Stop</button>
        ) : (
          <button type="submit">Send</button>
        )}
      </form>
    </main>
  )
}
```

Thanks to `useChat<ChatMessage>`, TypeScript knows that `part.output` is an `Order` in the `tool-getOrder` branch and that `part.input.orderId` is a string. When I used the output with the wrong type on purpose, the type check failed, which is what you want when tools and UI change separately.

Ask "Where's order A1001?" and the model calls `getOrder`, the card replaces the placeholder, and a second step adds a sentence such as "It arrives on Thursday."

You don't need a component library for this. Vercel's AI Elements, a set of chat components built on shadcn/ui, is moving to shadcn/ui and will be deprecated at the end of November 2026, so I'd build on your own components or on shadcn/ui directly.

## How to ask for approval before a tool runs

Set `toolApproval: { cancelOrder: "user-approval" }` on `streamText`. The tool part then stops in the `approval-requested` state. Your UI calls `addToolApprovalResponse`, and `useChat` sends the answer back so the server runs, or skips, the tool.

This is what happens when the user types "Cancel it":

1. The model calls `cancelOrder`. The server doesn't run it, and streams a `tool-cancelOrder` part in the `approval-requested` state.
2. The page shows "Cancel order A1001?" with two buttons.
3. A click calls `addToolApprovalResponse({ id: part.approval.id, approved })`, and the part moves to `approval-responded`.
4. Because of `sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses`, `useChat` posts the conversation again on its own.
5. The server sees the approval and runs the tool, or, if it was denied, tells the model the call was refused. The model then writes its answer in the same assistant message.

I tested this flow with the mock model. The order still existed while the part sat in `approval-requested`, and it was deleted only after the approval came back.

`toolApproval` takes more than `"user-approval"`. A function per tool can approve small cases automatically and forward the rest to the user, and automatic decisions show up in the same states, with `part.approval.isAutomatic` set.

There's one catch. The client sends the whole history on every request, so a modified client could fabricate an approval. For anything that moves money or deletes data, add `experimental_toolApprovalSecret` (shown in the checklist) so the server only accepts approvals it signed. Approvals are also how I'd gate tools that write through an MCP server, which I covered in [MCP servers for SaaS](https://liviu.dev/blog/8/mcp-server-for-saas-chatgpt-claude). The AI SDK can use any MCP server's tools through `createMCPClient` from `@ai-sdk/mcp`.

## How to set up the AI SDK in Nuxt

Nuxt uses the same server code with an h3 handler, and `@ai-sdk/vue` provides `useChat` as a Vue composable. The tools and the message type don't change.

### 1. Create the app and install the packages

```bash
pnpm create nuxt my-ai-app
cd my-ai-app
pnpm add ai @ai-sdk/vue zod
```

### 2. Put the key in runtime config

```bash
# .env
NUXT_AI_GATEWAY_API_KEY=your-key
```

```ts
// nuxt.config.ts
export default defineNuxtConfig({
  runtimeConfig: {
    aiGatewayApiKey: "", // filled from NUXT_AI_GATEWAY_API_KEY
  },
})
```

The `NUXT_` prefix lets Nuxt override `runtimeConfig.aiGatewayApiKey` at runtime, so the key is never in the client bundle.

### 3. Move the tools to the server

Copy `lib/orders.ts` and `lib/ai/tools.ts` from the Next.js section to `server/ai/orders.ts` and `server/ai/tools.ts`, and change one import in the tools file:

```ts
// server/ai/tools.ts
import { cancelOrder, findOrder } from "./orders"
```

I keep them out of `server/utils` on purpose. Nuxt auto-imports everything in that folder across the server, and I'd rather see where `tools` comes from.

### 4. Write the API route

```ts
// server/api/chat.post.ts
import {
  convertToModelMessages,
  createGateway,
  createUIMessageStreamResponse,
  isStepCount,
  streamText,
  toUIMessageStream,
  validateUIMessages,
} from "ai"
import { tools, type ChatMessage } from "~~/server/ai/tools"

export default defineLazyEventHandler(() => {
  const apiKey = useRuntimeConfig().aiGatewayApiKey
  if (!apiKey) throw new Error("Missing NUXT_AI_GATEWAY_API_KEY")
  const gateway = createGateway({ apiKey })

  return defineEventHandler(async (event) => {
    const userId = await getUserId(event) // your auth, from server/utils
    if (!userId) throw createError({ statusCode: 401 })

    const body = await readBody(event)
    const messages = await validateUIMessages<ChatMessage>({ messages: body.messages, tools })

    const result = streamText({
      model: gateway("anthropic/claude-sonnet-5.5"),
      instructions:
        "You are the support assistant of an online shop. Use the tools to look up and cancel orders. Keep answers short.",
      messages: await convertToModelMessages(messages),
      tools,
      toolsContext: {
        getOrder: { userId },
        cancelOrder: { userId },
      },
      toolApproval: { cancelOrder: "user-approval" },
      stopWhen: isStepCount(5),
    })

    return createUIMessageStreamResponse({
      stream: toUIMessageStream({ stream: result.stream }),
    })
  })
})
```

`defineLazyEventHandler` creates the gateway once, on the first request, and h3 sends the returned `Response` as it is, stream included. `getUserId` is a function of yours in `server/utils`, such as one built on `getUserSession` from nuxt-auth-utils.

### 5. Add the card component

```vue
<!-- app/components/OrderCard.vue -->
<script setup lang="ts">
import type { Order } from "~~/server/ai/orders"

defineProps<{ order: Order }>()
</script>

<template>
  <article class="rounded-lg border p-4">
    <h3 class="font-semibold">Order {{ order.id }}</h3>
    <p>{{ order.status === "delivered" ? "Delivered" : `Arrives ${order.eta}` }}</p>
    <p>Total: {{ order.total }}</p>
  </article>
</template>
```

The type-only import from `server/` is erased at build time, so no server code reaches the browser.

### 6. Build the chat page

```vue
<!-- app/pages/index.vue -->
<script setup lang="ts">
import { useChat } from "@ai-sdk/vue"
import { lastAssistantMessageIsCompleteWithApprovalResponses } from "ai"
import type { ChatMessage } from "~~/server/ai/tools"

const input = ref("")
const { messages, sendMessage, addToolApprovalResponse, status, stop } = useChat<ChatMessage>({
  sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses,
})
const busy = computed(() => status.value === "submitted" || status.value === "streaming")

function onSubmit() {
  if (!input.value.trim()) return
  sendMessage({ text: input.value })
  input.value = ""
}
</script>

<template>
  <main class="mx-auto max-w-xl p-6">
    <div v-for="message in messages" :key="message.id" class="mb-4">
      <strong>{{ message.role === "user" ? "You" : "Assistant" }}</strong>

      <template v-for="(part, i) in message.parts" :key="`${message.id}-${i}`">
        <p v-if="part.type === 'text'">{{ part.text }}</p>

        <template v-else-if="part.type === 'tool-getOrder'">
          <OrderCard v-if="part.state === 'output-available'" :order="part.output" />
          <p v-else-if="part.state === 'output-error'" role="alert">{{ part.errorText }}</p>
          <p v-else>Looking up the order…</p>
        </template>

        <template v-else-if="part.type === 'tool-cancelOrder'">
          <div v-if="part.state === 'approval-requested'">
            <p>Cancel order {{ part.input.orderId }}?</p>
            <button @click="addToolApprovalResponse({ id: part.approval.id, approved: true })">Cancel it</button>
            <button @click="addToolApprovalResponse({ id: part.approval.id, approved: false })">Keep it</button>
          </div>
          <p v-else-if="part.state === 'output-available'">
            {{ part.output.cancelled ? `Order ${part.output.orderId} is cancelled.` : "That order can no longer be cancelled." }}
          </p>
          <p v-else-if="part.state === 'output-denied'">Order kept.</p>
        </template>
      </template>
    </div>

    <form @submit.prevent="onSubmit">
      <input v-model="input" placeholder="Ask about an order">
      <button v-if="busy" type="button" @click="stop()">Stop</button>
      <button v-else type="submit">Send</button>
    </form>
  </main>
</template>
```

In version 7, `useChat` in Vue returns refs. `messages`, `status` and `error` are `ShallowRef`s, unwrapped in the template and read with `.value` in the script. If the chat depends on reactive values, such as a chat ID from the route, pass a getter, `useChat(() => ({ … }))`, and the composable recreates the chat when they change.

The `v-if` chain narrows the part type the same way the React `switch` does, and `vue-tsc` checks the template too. When I misspelt `part.approval.id` on purpose, the type check failed.

## What differs between Next.js and Nuxt?

Very little. The tools, the message type and the streaming protocol are the same; only the framework glue changes.

<table>
<thead>
  <tr>
    <th>
      
    </th>
    
    <th>
      Next.js
    </th>
    
    <th>
      Nuxt
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Client package
    </td>
    
    <td>
      <code>
        @ai-sdk/react
      </code>
    </td>
    
    <td>
      <code>
        @ai-sdk/vue
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      Chat state
    </td>
    
    <td>
      Plain values from <code>
        useChat
      </code>
    </td>
    
    <td>
      Refs from <code>
        useChat
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      Route
    </td>
    
    <td>
      <code>
        app/api/chat/route.ts
      </code>
      
      , exporting <code>
        POST
      </code>
    </td>
    
    <td>
      <code>
        server/api/chat.post.ts
      </code>
      
      , an h3 handler
    </td>
  </tr>
  
  <tr>
    <td>
      Reading the body
    </td>
    
    <td>
      <code>
        await req.json()
      </code>
    </td>
    
    <td>
      <code>
        await readBody(event)
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      Gateway key
    </td>
    
    <td>
      <code>
        AI_GATEWAY_API_KEY
      </code>
      
      , read automatically
    </td>
    
    <td>
      <code>
        NUXT_AI_GATEWAY_API_KEY
      </code>
      
       through <code>
        runtimeConfig
      </code>
      
       and <code>
        createGateway
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      Client boundary
    </td>
    
    <td>
      <code>
        "use client"
      </code>
      
       on the page
    </td>
    
    <td>
      None; the composable runs where the component runs
    </td>
  </tr>
  
  <tr>
    <td>
      Rendering parts
    </td>
    
    <td>
      <code>
        switch (part.type)
      </code>
      
       in JSX
    </td>
    
    <td>
      A <code>
        v-if
      </code>
      
       chain in the template
    </td>
  </tr>
</tbody>
</table>

If you're picking the framework rather than the SDK, I compared them in [React vs Vue in 2026](https://liviu.dev/blog/4/react-vs-vue).

## AI SDK production checklist

A chat that works on localhost is about a third of the job. Before real users get it, I go through this list:

1. **Authenticate the route** and take the user from the session. Pass whatever tools need through `toolsContext`, never through the prompt.
2. **Validate the history** with `validateUIMessages` and your tools. Return a 400 when it throws, rather than a 500.
3. **Keep tool errors safe.** Throw short messages from `execute`, and log the details on the server. `redactToolErrors: true` replaces the text that reaches the client, with a caveat for reasoning models in the docs.
4. **Gate every write with toolApproval,** and sign approvals with `experimental_toolApprovalSecret`.
5. **Cap the loop and the clock** with `isStepCount`, a `timeout`, and `maxDuration` on Vercel.
6. **Rate-limit per user** and record token usage from `onEnd`, so one user can't run up the bill.
7. **Save conversations** with `originalMessages` and `onEnd` on `toUIMessageStream`, so a reload doesn't lose the chat.
8. **Trace calls** with `registerTelemetry` and an integration such as `@ai-sdk/otel`.
9. **Test without an API key.** `MockLanguageModelV4` from `ai/test` and `simulateReadableStream` script the model's replies, tool calls included. That's how I checked the routes in this post.
10. **Upgrade on purpose.** Keep `ai` and `@ai-sdk/react` or `@ai-sdk/vue` on the same release line, and run the codemod for major versions.

Items 3, 4, 5 and 7 together look like this. I type-checked it as a full route against `ai` 7.0.173:

```ts
const result = streamText({
  // model, instructions, messages, tools, toolsContext and toolApproval as before
  experimental_toolApprovalSecret: process.env.TOOL_APPROVAL_SECRET,
  stopWhen: isStepCount(5),
  timeout: { totalMs: 60_000, stepMs: 20_000, toolMs: 10_000 },
})

return createUIMessageStreamResponse({
  stream: toUIMessageStream({
    stream: result.stream,
    redactToolErrors: true,
    originalMessages: messages,
    onEnd: ({ messages }) => saveChat({ chatId: body.id, messages }),
  }),
})
```

`saveChat` is yours to write, for example a table of chats keyed by the chat ID `useChat` sends with each request. If the app around the chat was itself built quickly with AI tools, my [production checklist for vibe-coded apps](https://liviu.dev/blog/7/vibe-coded-app-production-checklist) covers the rest, from auth and data access rules to secrets and monitoring.

## Where I can help

I add AI features to Nuxt and React products, from a first assistant to agents with tools and approvals, working from Romania with teams in the EU, UK and US. If you're planning an AI SDK chat, or one that works in a demo and not yet in production, these pages cover how I work:

- [AI integration](https://liviu.dev/services/ai-integration)
- [Nuxt development](https://liviu.dev/services/nuxt-development)
- [React and Next.js development](https://liviu.dev/services/react-nextjs-development)

Tell me what you're building and [get a quote](https://liviu.dev/hire-me?service=ai-integration). I'll reply within one working day.

## FAQ

### Is the Vercel AI SDK free?

Yes. It's open source under the Apache-2.0 licence and installs from npm. You pay only for model usage, either to the provider directly or through the Vercel AI Gateway.

### Do I need to deploy on Vercel to use the AI SDK?

No. It's a library, and its route handlers return standard `Response` objects that run on any Node.js 22+ host. The AI Gateway is optional too, since any provider package, such as `@ai-sdk/openai`, works without it.

### Does the AI SDK work with Nuxt and Vue?

Yes. `@ai-sdk/vue` provides `useChat`, `useCompletion` and `useObject` as composables. Since version 7, Vue uses the `useChat` composable, which returns refs; the older `Chat` class is deprecated. The server side is a normal Nuxt API route.

### What's the difference between AI SDK Core and AI SDK UI?

AI SDK Core (the `ai` package) runs on the server and calls models with `streamText`, `generateText`, tools and agents. AI SDK UI (`@ai-sdk/react`, `@ai-sdk/vue` and the others) runs in the browser, keeps the chat state and renders the streamed reply with `useChat`.

### What is generative UI in the AI SDK?

It's rendering your own components from the model's tool calls. The model calls a tool such as `getOrder`, the result reaches the client as a typed `tool-getOrder` part, and you render a component, such as an order card, when its state is `output-available`.

### How do I upgrade from AI SDK 6 to 7?

Move to Node.js 22 and ESM, update `ai` and your `@ai-sdk/*` packages together, then run `npx @ai-sdk/codemod v7`. It renames `system` to `instructions`, `stepCountIs` to `isStepCount` and `onFinish` to `onEnd`, among others. Check anything left by hand against the official migration guide.

## Sitemap

See the full [sitemap](https://liviu.dev/sitemap.md) for all pages.
