@convex-dev/persistent-text-streaming

中文文档
0.3.5发布于 2026/10/23Apache-2.0TypeScriptES Module零依赖近 30 天下载 23.4万

A Convex component for streaming durable text to the client, from LLMs and other sources.

原始使用文档
文档目录6 节
  1. Pre-requisite: Convex
  2. Installation
  3. Usage
  4. Svelte (beta)
  5. Design Philosophy
  6. Background

Convex Component: Persistent Text Streaming

npm version

This Convex component enables persistent text streaming. It provides a React hook for streaming text from HTTP actions while simultaneously storing the data in the database. This persistence allows the text to be accessed after the stream ends or by other users.

The most common use case is for AI chat applications. The example app (found in the example directory) is a just such a simple chat app that demonstrates use of the component.

Here's what you'll end up with! The left browser window is streaming the chat body to the client, and the right browser window is subscribed to the chat body via a database query. The message is only updated in the database on sentence boundaries, whereas the HTTP stream sends tokens as they come:

example-animation

Pre-requisite: Convex

You'll need an existing Convex project to use the component. Convex is a hosted backend platform, including a database, serverless functions, and a ton more you can learn about here.

Run npm create convex or follow any of the quickstarts to set one up.

Installation

See example/ for a working demo.

  1. Install the Persistent Text Streaming component:
npm install @convex-dev/persistent-text-streaming
  1. Create a convex.config.ts file in your app's convex/ folder and install the component by calling use:
// convex/convex.config.ts
import { defineApp } from "convex/server";
import persistentTextStreaming from "@convex-dev/persistent-text-streaming/convex.config.js";

const app = defineApp();
app.use(persistentTextStreaming);
export default app;

Usage

Here's a simple example of how to use the component:

In convex/chat.ts:

const persistentTextStreaming = new PersistentTextStreaming(
  components.persistentTextStreaming,
);

// Create a stream using the component and store the id in the database with
// our chat message.
export const createChat = mutation({
  args: {
    prompt: v.string(),
  },
  handler: async (ctx, args) => {
    const streamId = await persistentTextStreaming.createStream(ctx);
    const chatId = await ctx.db.insert("chats", {
      title: "...",
      prompt: args.prompt,
      stream: streamId,
    });
    return chatId;
  },
});

// Create a query that returns the chat body.
export const getChatBody = query({
  args: {
    streamId: StreamIdValidator,
  },
  handler: async (ctx, args) => {
    return await persistentTextStreaming.getStreamBody(
      ctx,
      args.streamId as StreamId,
    );
  },
});

// Create an HTTP action that generates chunks of the chat body
// and uses the component to stream them to the client and save them to the database.
export const streamChat = httpAction(async (ctx, request) => {
  const body = (await request.json()) as { streamId: string };
  const generateChat = async (ctx, request, streamId, chunkAppender) => {
    await chunkAppender("Hi there!");
    await chunkAppender("How are you?");
    await chunkAppender("Pretend I'm an AI or something!");
  };

  const response = await persistentTextStreaming.stream(
    ctx,
    request,
    body.streamId as StreamId,
    generateChat,
  );

  // Set CORS headers appropriately.
  response.headers.set("Access-Control-Allow-Origin", "*");
  response.headers.set("Vary", "Origin");
  return response;
});

You need to expose this HTTP endpoint in your backend, so in convex/http.ts:

http.route({
  path: "/chat-stream",
  method: "POST",
  handler: streamChat,
});

// Handle CORS preflight requests so browsers will allow the POST above when
// your app is served from a different origin than your Convex deployment.
http.route({
  path: "/chat-stream",
  method: "OPTIONS",
  handler: httpAction(async (_, request) => {
    const headers = request.headers;
    if (
      headers.get("Origin") !== null &&
      headers.get("Access-Control-Request-Method") !== null &&
      headers.get("Access-Control-Request-Headers") !== null
    ) {
      return new Response(null, {
        headers: new Headers({
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Methods": "POST",
          "Access-Control-Allow-Headers": "Content-Type, Digest, Authorization",
          "Access-Control-Max-Age": "86400",
        }),
      });
    } else {
      return new Response();
    }
  }),
});

Finally, in your app, you can now create chats and them subscribe to them via stream and/or database query as optimal:

// chat-input.tsx, maybe?
const createChat = useMutation(api.chat.createChat);
const formSubmit = async (e: React.FormEvent) => {
  e.preventDefault();
  const chatId = await createChat({
    prompt: inputValue,
  });
};

// chat-message.tsx, maybe?
import { useStream } from "@convex-dev/persistent-text-streaming/react";

// ...

// In our component:
const { text, status } = useStream(
  api.chat.getChatBody, // The query to call for the full stream body
  new URL(`${convexSiteUrl}/chat-stream`), // The HTTP endpoint for streaming
  driven, // True if this browser session created this chat and should generate the stream
  chat.streamId as StreamId, // The streamId from the chat database record
);

Svelte (beta)

Svelte 5 bindings are community-supported and in beta. They need svelte and convex-svelte, with setupConvex called in a parent component. Reactive inputs are passed as getters. See example-svelte/ for the chat app.

<script lang="ts">
  import { useStream } from "@convex-dev/persistent-text-streaming/svelte";

  let { chat, driven }: { chat: Doc<"chats">; driven: boolean } = $props();

  const stream = useStream(
    api.chat.getChatBody,
    new URL(`${convexSiteUrl}/chat-stream`),
    () => driven,
    () => chat.streamId as StreamId,
    // Optional, read when a stream starts:
    // () => ({ authToken, headers }),
  );
</script>

<p>{stream.text}</p>

stream.text and stream.status update as the stream progresses. The HTTP request only starts in the browser, never during server-side rendering.

Design Philosophy

This component balances HTTP streaming with database persistence to try to maximize the benefits of both. To understand why this balance is beneficial, let's examine each approach in isolation.

  • HTTP streaming only: If your app only uses HTTP streaming, then the original browser that made the request will have a great, high-performance streaming experience. But if that HTTP connection is lost, if the browser window is reloaded, if other users want to view the same chat, or this users wants to revisit the conversation later, it won't be possible. The conversation is only ephemeral because it was never stored on the server.

  • Database Persistence Only: If your app only uses database persistence, it's true that the conversation will be available for as long as you want. Additionally, Convex's subscriptions will ensure the chat message is updated as new text chunks are generated. However, there are a few downsides: one, the entire chat body needs to be resent every time it is changed, which is a lot redundant bandwidth to push into the database and over the websockets to all connected clients. Two, you'll need to make a difficult tradeoff between interactivity and efficiency. If you write every single small chunk to the database, this will get quite slow and expensive. But if you batch up the chunks into, say, paragraphs, then the user experience will feel laggy.

This component combines the best of both worlds. The original browser that makes the request will still have a great, high-performance streaming experience. But the chat body is also stored in the database, so it can be accessed by the client even after the stream has finished, or by other users, etc.

Background

This component is largely based on the Stack post AI Chat with HTTP Streaming.

版本与发布记录

@convex-dev/persistent-text-streaming 共发布 14 个版本,首次发布于 2025/03/01;过去 12 个月发布了 6 个版本。

版本发布日期距今
0.3.5latest2026/10/2318 天前
0.3.42026/10/101 个月前
0.3.32026/06/254 个月前
0.3.22026/04/087 个月前
0.3.12026/04/087 个月前
0.3.02025/11/1311 个月前

其他发布通道:alpha → 0.2.3-alpha.0。

关于 @convex-dev/persistent-text-streaming 的常见问题

@convex-dev/persistent-text-streaming 是什么?

A Convex component for streaming durable text to the client, from LLMs and other sources.

如何安装 @convex-dev/persistent-text-streaming?

在项目目录运行 npm install @convex-dev/persistent-text-streaming,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:convex(^1.32.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@convex-dev/persistent-text-streaming 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@convex-dev/persistent-text-streaming 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@convex-dev/persistent-text-streaming 可以商用吗?

@convex-dev/persistent-text-streaming 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@convex-dev/persistent-text-streaming 的下载量有多少?

根据 npm 官方下载统计,@convex-dev/persistent-text-streaming 在 2026/10/11 – 2026/11/09 这 30 天内被下载 233,849 次,日均约 7,795 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@convex-dev/persistent-text-streaming 还在维护吗?

最新版本 0.3.5 发布于 2026/10/23(18 天前);至今共发布 14 个版本,其中过去 12 个月发布了 6 个;首次发布于 2025/03/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。