---
title: "Stream a response"
description: "Stream a metered answer to the page while it persists on the server: ai.stream on the backend, the /ai/stream endpoint, and useAiStream in Vue. Reload mid-stream and the text continues."
canonical_url: "https://nuxt-backend.dev/docs/build/ai/streaming"
---
# Stream a response

> Stream a metered answer to the page while it persists on the server: ai.stream on the backend, the /ai/stream endpoint, and useAiStream in Vue. Reload mid-stream and the text continues.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: how-to · Status: experimental

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

- [API reference](https://nuxt-backend.dev/docs/reference/api/use-ai-stream)
- [Source](https://github.com/qruto/nuxt-backend/blob/main/src/runtime/vue/composables/use-ai-stream.ts)

- **You get:** an answer that appears word by word, survives a reload or a second device, and costs nothing when it breaks off.
- **Powered by:** the AI SDK's `streamText`, Convex's persistent text streaming component, and an HTTP route on your deployment.
- **The package adds:** the metering around the stream (reserve, settle at the end, release on error or timeout), the `/ai/stream` endpoint, and `useAiStream` in Vue.

`ai.stream` is the streaming shape of a [metered action](https://nuxt-backend.dev/docs/build/ai/metered-actions): the same checks and the same credit reservation, but the handler sends the answer to the browser chunk by chunk, and every chunk also persists on the server through Convex's persistent text streaming. Reload mid-stream, or open the same stream on another device, and the text carries on from what the server kept. Credits settle only when the stream finishes. An error or a dropped connection releases them, so an interrupted stream costs nothing.

## Define the stream

```ts [backend/ai.ts]
export const { start: startEcho, body: echoBody } = ai.stream({
  name: 'echo',            // unique per app: the stream endpoint routes by it
  meter: 'credits',        // or false for a stream that is only rate-limited
  cost: 1,                 // the same shapes as a metered action's cost
  limit: 'ai',
  args: { prompt: v.string() },
  handler: async (ctx, { prompt }, { append }) => {
    for (const word of prompt.split(' ')) {
      await append(word + ' ')   // sends the chunk to the browser and persists it
    }
  },
})
```

`ai.stream` takes what `ai.meteredAction` takes, plus `name`: `meter`, `cost`, `limit`, `allowOverage` and `model` mean the same ([the options](https://nuxt-backend.dev/docs/build/ai/metered-actions#define-a-metered-action)). There is no `charge` option: a stream always settles when it finishes. Two shapes of `cost` settle after the run:

- `{ estimate, finalize }` prices what the handler **returns**, so return the model's token usage from it: see [Token pricing](https://nuxt-backend.dev/docs/build/ai/metered-actions#token-pricing).
- `{ estimate, creditsPerUsd }` settles at the cost the model calls through `ctx.model()` reported once the stream ends: see [Charge what a call cost](https://nuxt-backend.dev/docs/build/ai/models#charge-what-a-call-cost).

A model's answer, charged at what it cost:

```ts [backend/ai.ts]
import { streamText } from 'ai'

export const { start: startAnswer, body: answerBody } = ai.stream({
  name: 'answer',
  meter: 'credits',
  model: 'openai/gpt-5-mini',
  cost: { estimate: 5, creditsPerUsd: 1000, round: 'up', minimum: 1 },
  args: { prompt: v.string() },
  handler: async (ctx, { prompt }, { append }) => {
    const result = streamText({ model: ctx.model(), prompt })
    for await (const chunk of result.textStream) await append(chunk)
  },
})
```

A name used twice throws where the second `ai.stream` runs.

## What it serves

`ai.stream` returns two functions. Export them from your module under names of your choice:

- **start**, a public action: it runs the metered call's checks, reserves the credits, creates the persisted stream, records the request, arms the `streamTimeout` release, and returns `{ streamId }`.
- **body**, a public query taking `{ streamId }`: the persisted text and its status, live.

The third piece is the HTTP endpoint `registerBackendRoutes({ ai })` mounts at **/ai/stream**, which the scaffolded `backend/http.ts` already passes. It answers `POST` with `{ streamId }`, and `OPTIONS` for the browser's preflight, allowing the origin in `SITE_URL`. It looks the request up, refuses it with `404` unless it exists and is still reserved, claims it so a second `POST` of the same stream id answers `409` instead of running the model again, runs your handler with `ctx.usage`, and streams each `append` back.

The stream id is the key: it is unguessable, and the signed-in `start` action handed it to this caller moments before. Anyone holding it can read the stream's `body`, so share it only with the people who should read the answer.

## How a stream settles

<table>
<thead>
  <tr>
    <th>
      What happens
    </th>
    
    <th>
      Credits
    </th>
    
    <th>
      Request
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      The handler returns
    </td>
    
    <td>
      Settled at the final cost, the rest of the estimate handed back
    </td>
    
    <td>
      <code>
        settled
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      The handler throws, or the usage event cannot be sent
    </td>
    
    <td>
      Released
    </td>
    
    <td>
      <code>
        released
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      Every call through <code>
        ctx.model()
      </code>
      
       failed, though the handler returned
    </td>
    
    <td>
      Released; the stream ends in error (<code>
        unavailable
      </code>
      
      , reason <code>
        provider_refused
      </code>
      
      )
    </td>
    
    <td>
      <code>
        released
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        start
      </code>
      
       ran but nothing drove the stream (the tab closed first)
    </td>
    
    <td>
      Released when <code>
        streamTimeout
      </code>
      
       runs out (default 5 minutes)
    </td>
    
    <td>
      stays <code>
        reserved
      </code>
    </td>
  </tr>
</tbody>
</table>

`streamText` does not throw when its model call fails: it hands the error to its `onError` and ends `textStream` as if the answer were done. That is why a run whose every model call failed is released all the same. The `streamTimeout` release is scheduled at `start` and cancelled when the stream settles; set it on `setupAi`, or `false` to turn it off.

A person's stream requests are removed with their account's [erasure](https://nuxt-backend.dev/docs/build/auth/accounts/data#what-an-erasure-removes).

## Drive it from Vue

```vue
<script setup lang="ts">
import { api } from '#backend/api'

const echo = useAiStream({ start: api.ai.startEcho, body: api.ai.echoBody })
const prompt = ref('')
</script>

<template>
  <input v-model="prompt">
  <button :aria-disabled="echo.isStreaming.value || undefined" @click="echo.isStreaming.value || echo.start({ prompt })">Generate</button>
  <button v-if="echo.isStreaming.value" @click="echo.stop()">Stop</button>
  <pre>{{ echo.text.value }}</pre>
  <small>{{ echo.status.value }} · {{ echo.streamId.value }}</small>
</template>
```

`useAiStream(stream, options?)` returns:

<field-group>
<field name="start(args?)" type="Promise<string>">

Runs the `start` action, which checks the call and reserves the credits, then drives the stream with a `fetch` to `<convex site url>/ai/stream`. Resolves with the stream id as soon as driving begins. A refused start rejects with what the call threw, and `status` ends in `'error'`. A new `start` replaces the stream in flight.

</field>

<field name="stop()">

Aborts the driving fetch, or a start still waiting for the server, and `status` reads `'idle'` at once. The server releases the unfinished spend.

</field>

<field name="text" type="ComputedRef<string>">

The text so far: live from the driving fetch while this client drives, the persisted body otherwise.

</field>

<field name="status" type="ComputedRef<'idle' | 'pending' | 'streaming' | 'done' | 'error' | 'timeout'>">

The driving status, or the persisted stream's status when watching.

</field>

<field name="isPending" type="ComputedRef<boolean>">

`true` while `start` waits for the server to accept the stream.

</field>

<field name="isStreaming / streamId" type="ComputedRef">

Whether a stream is in flight, and the active stream's id: hand it to another client to watch along.

</field>

<field name="error" type="ComputedRef<BackendError | null>">

Why the last `start` failed: a refusal such as `insufficient_credits`, `rate_limited` or `unauthenticated` with its code, anything else as `unavailable` with reason `unexpected` (see [Composable conventions](https://nuxt-backend.dev/docs/reference/nuxt/conventions)). Else why the driving fetch failed, while the text keeps following the persisted body; else why the persisted body could not be read. Cleared when the next `start` begins.

</field>
</field-group>

Options: `streamId`, to attach to an existing stream as a viewer instead of driving a new one; `url`, to override the endpoint (default `<runtimeConfig.public.convex.siteUrl>/ai/stream`); and `headers`, extra headers on the driving fetch.

## Resume after a reload

Keep the stream id somewhere that survives the reload, such as the route's query, and pass it back:

```vue
<script setup lang="ts">
import { api } from '#backend/api'

const route = useRoute()
const echo = useAiStream(
  { start: api.ai.startEcho, body: api.ai.echoBody },
  { streamId: computed(() => route.query.stream as string | undefined) },
)
</script>
```

When the driving fetch fails part-way, on a dropped network for instance, `useAiStream` logs it and falls back to the persisted body: whatever the server already appended keeps showing, and the server settles or releases on its own, whatever the client does.

## Move the route

`registerBackendRoutes({ ai, aiPath: '/streams' })` serves the endpoint at another path; pass the matching `url` to `useAiStream`. When the app's origin is not `SITE_URL`, set `cors: { origin }` on `setupAi`.

## Related

- [Meter an AI action](https://nuxt-backend.dev/docs/build/ai/metered-actions): the checks, the reservation and the costs a stream shares.
- [Choose a model](https://nuxt-backend.dev/docs/build/ai/models): `ctx.model()`, `streamText` and costs the model reports.
- [AI gateway](https://nuxt-backend.dev/docs/services/ai-gateway): the model route, its keys and its spending cap.
- [HTTP routes](https://nuxt-backend.dev/docs/reference/backend/http-routes): every route `registerBackendRoutes` mounts.
- [`useAiStream` reference](https://nuxt-backend.dev/docs/reference/api/use-ai-stream).


## Sitemap

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