关于 rivetkit-client-javascript
面向浏览器、Node.js 和 Bun 开发者的技能,介绍如何通过 `rivetkit/client` 连接 Rivet Actors。内容涵盖 Actor 访问、连接配置、事件订阅及底层 HTTP 和 WebSocket 请求。
主要功能
- 01使用 `createClient()` 创建客户端
- 02按名称和键访问 Actor
- 03配置连接参数
- 04订阅 Actor 事件
- 05使用底层 HTTP 和 WebSocket API
适用场景
- 01构建调用 Rivet Actors 的浏览器应用
- 02让 Node.js 或 Bun 服务连接 Actor
- 03向 Actor 发送直接 HTTP 或 WebSocket 请求
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ rivet-dev/ skills --skill rivetkit-client-javascript安装后在 Claude Code 中输入/rivetkit-client-javascript确认已加载。
附带文件index.json
详细介绍
RivetKit JavaScript 客户端
构建连接 Rivet Actor 的 JavaScript 客户端(浏览器、Node.js 或 Bun)时,请使用此技能,并通过 rivetkit/client 进行连接。
入门步骤
- 安装客户端(最新版本:2.3.7)
npm install [email protected] - 使用
createClient()创建客户端并调用 Actor 操作。
错误处理策略
- 默认优先采用快速失败行为。
- 除非绝对必要,否则避免使用
try/catch。 - 如果使用了
catch,请明确处理错误,至少将其记录到日志中。
开始使用
请参阅后端快速入门指南以开始使用。
最简客户端
无状态与有状态
获取 Actor
连接参数
静态连接参数请使用 params。如果值可能在不同连接尝试之间变化,例如在每次 .connect() 或重新连接前刷新 JWT,请使用 getParams。
订阅事件
连接生命周期
底层 HTTP 和 WebSocket
对于实现了 onRequest 或 onWebSocket 的 Actor,请直接调用它们:
import { createClient } from "rivetkit/client";
const client = createClient();
const handle = client.chatRoom.getOrCreate(["general"]);
const response = await handle.fetch("history");
const history = await response.json();
const ws = await handle.webSocket("stream");
ws.addEventListener("message", (event) => {
console.log("message:", event.data);
});
ws.send("hello");
从后端调用
错误处理
概念
键
键用于唯一标识 Actor 实例。使用复合键(数组)进行分层寻址:
当 userId 包含用户数据时,不要使用字符串插值(如 "org:${userId}")构造键。请改用数组,以防止键注入攻击。
环境变量
createClient() 会自动读取:
RIVET_ENDPOINT(端点)RIVET_NAMESPACERIVET_TOKENRIVET_POOL
未设置时,默认值为 http://localhost:6420。RivetKit 默认在端口 6420 上运行。
端点格式
端点支持 URL 身份验证语法:
https://namespace:[email protected]
你也可以传入不含身份验证信息的端点,并分别提供 RIVET_NAMESPACE 和 RIVET_TOKEN。对于无服务器部署,请使用应用的 /api/rivet URL。详情请参阅端点。
高级用法
跳过就绪等待
通常,请求会在网关处等待,直到 Actor 准备好接收流量。Actor 在启动期间(onWake 尚未完成)或处于睡眠宽限期期间(正在运行 onSleep、waitUntil,且仍有待处理的断开连接)都尚未就绪。
在底层 HTTP 和 WebSocket API 中传入 skipReadyWait: true,即可立即发送请求,并在上述任一期间到达 Actor 的 onRequest / onWebSocket 处理程序:
import { createClient } from "rivetkit/client";
const client = createClient();
const handle = client.chatRoom.getOrCreate(["general"]);
const response = await handle.fetch("/healthz", {
skipReadyWait: true,
});
const ws = await handle.webSocket("probe", undefined, {
skipReadyWait: true,
});
请求仍可能返回暂时性的生命周期或网关错误。请等 Actor 再次可用后重试。
actor.stopping:Actor 已完全停止,即睡眠宽限期已结束,但尚未重新启动。guard.actor_stopped_while_waiting:请求已到达 Actor 隧道,但 Actor 在网关收到响应前停止了。guard.tunnel_request_aborted:Actor 隧道在响应开始前中止了请求。guard.tunnel_message_timeout:隧道消息超时后,网关丢弃了正在进行的隧道请求。guard.tunnel_response_closed:Actor 隧道在发送响应前关闭。guard.gateway_response_start_timeout:网关等待 Actor 响应开始时超时。
API 参考
软件包: rivetkit
请参阅 RivetKit 客户端概览。
createClient- 创建客户端Client- 客户端类型
需要客户端之外的内容?
如果你还需要了解 Rivet Actor、注册表或服务端 RivetKit,请添加主技能:
npx skills add rivet-dev/skills
然后使用 rivetkit 技能获取后端指导。