rivetkit-client-javascript

Par rivet-dev · skills

Guide du client JavaScript RivetKit. À utiliser pour les clients browser, Node.js ou Bun qui se connectent aux Rivet Actors avec rivetkit/client, créent des clients, appellent des actions ou gèrent des connexions.

npx skills add https://github.com/rivet-dev/skills --skill rivetkit-client-javascript

Client JavaScript RivetKit

Utilise cette skill pour créer des clients JavaScript (navigateur, Node.js ou Bun) qui se connectent à des Rivet Actors avec rivetkit/client.

Premiers pas

  1. Installe le client (dernière version : 2.2.0)
    npm install rivetkit@2.2.0
  2. Crée un client avec createClient() et appelle les actions des actors.

Politique de gestion des erreurs

  • Préfère un comportement fail-fast par défaut.
  • Évite try/catch sauf si absolument nécessaire.
  • Si un catch est utilisé, gère l'erreur explicitement, au minimum en la journalisant.

Démarrage

Voir le guide de démarrage backend pour commencer.

Client minimal

import { createClient } from "rivetkit/client";
import type { registry } from "./index";

const client = createClient<typeof registry>({
  endpoint: "https://my-namespace:pk_...@api.rivet.dev",
});
const counter = client.counter.getOrCreate(["my-counter"]);
const count = await counter.increment(1);
import { actor, setup } from "rivetkit";

export const counter = actor({
  state: { count: 0 },
  actions: {
    increment: (c, x: number) => {
      c.state.count += x;
      return c.state.count;
    },
  },
});

export const registry = setup({
  use: { counter },
});

registry.start();

Stateless vs Stateful

import { createClient } from "rivetkit/client";

const client = createClient();
const handle = client.counter.getOrCreate(["my-counter"]);

// Stateless: chaque appel est indépendant
await handle.increment(1);

// Stateful: garde une connexion ouverte pour les événements en temps réel
const conn = handle.connect();
conn.on("count", (value) => console.log(value));
await conn.increment(1);

Récupérer des Actors

import { createClient } from "rivetkit/client";

const client = createClient();
const room = client.chatRoom.getOrCreate(["room-42"]);
const existing = client.chatRoom.get(["room-42"]);

const created = await client.game.create(["game-1"], {
  input: { mode: "ranked" },
});

const byId = client.chatRoom.getForId("actor-id");
const resolvedId = await room.resolve();

Paramètres de connexion

import { createClient } from "rivetkit/client";

const client = createClient();
const chat = client.chatRoom.getOrCreate(["general"], {
  params: { authToken: "jwt-token-here" },
});

const conn = chat.connect();
import { createClient } from "rivetkit/client";

async function getAuthToken(): Promise<string> {
  return "jwt-token-here";
}

const client = createClient();
const chat = client.chatRoom.getOrCreate(["general"], {
  getParams: async () => ({
    authToken: await getAuthToken(),
  }),
});

const conn = chat.connect();

Utilise params pour les paramètres de connexion statiques. Utilise getParams quand la valeur peut changer entre les tentatives de connexion, par exemple pour rafraîchir un JWT avant chaque .connect() ou reconnexion.

S'abonner à des événements

import { createClient } from "rivetkit/client";

const client = createClient();
const conn = client.chatRoom.getOrCreate(["general"]).connect();
conn.on("message", (msg) => console.log(msg));
conn.once("gameOver", () => console.log("done"));

Cycle de vie de la connexion

import { createClient } from "rivetkit/client";

const client = createClient();
const conn = client.chatRoom.getOrCreate(["general"]).connect();

conn.onOpen(() => console.log("connected"));
conn.onClose(() => console.log("disconnected"));
conn.onError((err) => console.error("error:", err));
conn.onStatusChange((status) => console.log("status:", status));

await conn.dispose();

HTTP et WebSocket bas niveau

Pour les actors qui implémentent onRequest ou onWebSocket, les appelle directement :

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");

Appels depuis le Backend

import { Hono } from "hono";
import { createClient } from "rivetkit/client";

const app = new Hono();
const client = createClient();

app.post("/increment/:name", async (c) => {
  const counterHandle = client.counter.getOrCreate([c.req.param("name")]);
  const newCount = await counterHandle.increment(1);
  return c.json({ count: newCount });
});

Gestion des erreurs

import { ActorError } from "rivetkit/client";
import { createClient } from "rivetkit/client";

const client = createClient();

try {
  await client.user.getOrCreate(["user-123"]).updateUsername("ab");
} catch (error) {
  if (error instanceof ActorError) {
    console.log(error.code, error.metadata);
  }
}

Concepts

Clés

Les clés identifient de manière unique les instances d'actors. Utilise des clés composées (tableaux) pour l'adressage hiérarchique :

import { createClient } from "rivetkit/client";
import type { registry } from "./index";

const client = createClient<typeof registry>("http://localhost:6420");

// Clé composée : [org, room]
client.chatRoom.getOrCreate(["org-acme", "general"]);
import { actor, setup } from "rivetkit";

export const chatRoom = actor({
  state: { messages: [] as string[] },
  actions: {
    getRoomInfo: (c) => ({ org: c.key[0], room: c.key[1] }),
  },
});

export const registry = setup({
  use: { chatRoom },
});

registry.start();

Ne construis pas les clés avec interpolation de chaîne comme "org:${userId}" quand userId contient des données utilisateur. Utilise plutôt des tableaux pour prévenir les attaques par injection de clé.

Variables d'environnement

createClient() lit automatiquement :

  • RIVET_ENDPOINT (endpoint)
  • RIVET_NAMESPACE
  • RIVET_TOKEN
  • RIVET_RUNNER

Par défaut http://localhost:6420 quand non défini. RivetKit s'exécute par défaut sur le port 6420.

Format d'endpoint

Les endpoints supportent la syntaxe d'authentification URL :

https://namespace:token@api.rivet.dev

Tu peux aussi passer l'endpoint sans authentification et fournir RIVET_NAMESPACE et RIVET_TOKEN séparément. Pour les déploiements serverless, utilise l'URL /api/rivet de ton application. Voir Endpoints pour les détails.

Référence API

Package : rivetkit

Voir l'aperçu du client RivetKit.

Besoin de plus que le Client ?

Si tu as besoin de plus sur les Rivet Actors, les registries ou RivetKit côté serveur, ajoute la skill principale :

npx skills add rivet-dev/skills

Puis utilise la skill rivetkit pour les conseils backend.

Skills similaires