Skip to content
This repository was archived by the owner on Oct 22, 2025. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 40 additions & 4 deletions docs/workers/quickstart.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,18 @@ export const registry = setup({
import { registry } from "./registry";
import { Hono } from "hono";
import { serve } from "@hono/node-server";
import { createNodeWebSocket } from '@hono/node-ws'

// Setup server
const app = new Hono();

// Start RivetKit
//
// State is stored in memory, this can be configured later
const { client, hono } = registry.run();

// Setup server
const app = new Hono();
const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app }) // TODO: do this before app
const { client, hono } = registry.run({
getUpgradeWebSocket: () => upgradeWebSocket,
});

// Expose RivetKit to the frontend (optional)
app.route("/registry", hono);
Expand All @@ -67,6 +71,7 @@ app.post("/increment/:name", async (c) => {
serve({ fetch: app.fetch, port: 8080 }, (x) =>
console.log("Listening at http://localhost:8080"),
);
injectWebSocket(server)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The server variable is undefined at this point. The serve function call on lines 67-69 doesn't assign its return value to a variable, so injectWebSocket(server) will throw a ReferenceError. Consider capturing the return value from serve first:

const server = serve({ fetch: app.fetch, port: 8080 }, (x) =>
  console.log("Listening at http://localhost:8080"),
);
injectWebSocket(server);
Suggested change
injectWebSocket(server)
const server = serve({ fetch: app.fetch, port: 8080 }, (x) =>
console.log("Listening at http://localhost:8080"),
);
injectWebSocket(server);

Spotted by Diamond

Is this helpful? React 👍 or 👎 to let us know.

```

```ts Express.js
Expand All @@ -77,6 +82,37 @@ TODO
TODO
```

```ts Hono
import { registry } from "./registry";
import { Hono } from "hono";

// Start RivetKit
//
// State is stored in memory, this can be configured later
const { client, serve } = registry.server();

// Setup server
const app = new Hono();

// Example endpoint
app.post("/increment/:name", async (c) => {
const name = c.req.param("name");

// Communicate with actor
const counter = client.counter.getOrCreate(name);
const newCount = await counter.increment(1);

return c.text(`New Count: ${newCount}`);
});

// Start server
serve(app);
```

TODO: How to serve without registry helper

TODO: Why we need to use our own custom serve fn

</CodeGroup>

<Info>
Expand Down
6 changes: 0 additions & 6 deletions examples/better-auth/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,11 @@
},
"dependencies": {
"@hono/node-server": "^1.14.4",
"@rivetkit/memory": "workspace:0.9.0-rc.1",
"@rivetkit/react": "workspace:0.9.0-rc.1",
"better-auth": "^1.0.1",
"hono": "^4.7.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"example": {
"platforms": [
"*"
]
},
"stableVersion": "0.8.0"
}
40 changes: 20 additions & 20 deletions examples/better-auth/src/backend/auth.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import { betterAuth } from "better-auth";
import { sqliteAdapter } from "@better-auth/sqlite";
import Database from "better-sqlite3";

const db = new Database("./auth.db");

export const auth = betterAuth({
database: sqliteAdapter(db),
emailAndPassword: {
enabled: true,
},
session: {
expiresIn: 60 * 60 * 24 * 7, // 7 days
updateAge: 60 * 60 * 24, // 1 day (every day the session expiry is updated)
},
plugins: [],
});

export type Session = typeof auth.$Infer.Session;
export type User = typeof auth.$Infer.User;
// import { betterAuth } from "better-auth";
// import { sqliteAdapter } from "@better-auth/sqlite";
// import Database from "better-sqlite3";
//
// const db = new Database("./auth.db");
//
// export const auth = betterAuth({
// database: sqliteAdapter(db),
// emailAndPassword: {
// enabled: true,
// },
// session: {
// expiresIn: 60 * 60 * 24 * 7, // 7 days
// updateAge: 60 * 60 * 24, // 1 day (every day the session expiry is updated)
// },
// plugins: [],
// });
//
// export type Session = typeof auth.$Infer.Session;
// export type User = typeof auth.$Infer.User;
96 changes: 48 additions & 48 deletions examples/better-auth/src/backend/registry.ts
Original file line number Diff line number Diff line change
@@ -1,48 +1,48 @@
import { worker, setup } from "@rivetkit/worker";
import { auth, type Session, type User } from "./auth";

export const chatRoom = worker({
onAuth: async (c) => {
const authResult = await auth.api.getSession({
headers: c.req.headers,
});

if (!authResult?.session || !authResult?.user) {
throw new Error("Unauthorized");
}

return {
userId: authResult.user.id,
user: authResult.user,
session: authResult.session,
};
},
state: {
messages: [] as Array<{ id: string; userId: string; username: string; message: string; timestamp: number }>
},
actions: {
sendMessage: (c, message: string) => {
const newMessage = {
id: crypto.randomUUID(),
userId: c.auth.userId,
username: c.auth.user.email,
message,
timestamp: Date.now(),
};
c.state.messages.push(newMessage);
c.broadcast("newMessage", newMessage);
return newMessage;
},
getMessages: (c) => {
return c.state.messages;
},
},
});

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

export type Registry = typeof registry;
// import { worker, setup } from "@rivetkit/worker";
// import { auth, type Session, type User } from "./auth";
//
// export const chatRoom = worker({
// onAuth: async (c) => {
// const authResult = await auth.api.getSession({
// headers: c.req.headers,
// });
//
// if (!authResult?.session || !authResult?.user) {
// throw new Error("Unauthorized");
// }
//
// return {
// userId: authResult.user.id,
// user: authResult.user,
// session: authResult.session,
// };
// },
// state: {
// messages: [] as Array<{ id: string; userId: string; username: string; message: string; timestamp: number }>
// },
// actions: {
// sendMessage: (c, message: string) => {
// const newMessage = {
// id: crypto.randomUUID(),
// userId: c.auth.userId,
// username: c.auth.user.email,
// message,
// timestamp: Date.now(),
// };
//
// c.state.messages.push(newMessage);
// c.broadcast("newMessage", newMessage);
//
// return newMessage;
// },
// getMessages: (c) => {
// return c.state.messages;
// },
// },
// });
//
// export const registry = setup({
// workers: { chatRoom },
// });
//
// export type Registry = typeof registry;
109 changes: 54 additions & 55 deletions examples/better-auth/src/backend/server.ts
Original file line number Diff line number Diff line change
@@ -1,55 +1,54 @@
import { registry } from "./registry";
import { auth } from "./auth";
import { Hono } from "hono";
import { serve } from "@hono/node-server";
import { createMemoryDriver } from "@rivetkit/memory";

// Setup router
const app = new Hono();

// Start RivetKit
const { client, hono } = registry.run({
driver: createMemoryDriver(),
cors: {
// IMPORTANT: Configure origins in production
origin: "*",
},
});

// Mount Better Auth routes
app.on(["GET", "POST"], "/api/auth/**", (c) => auth.handler(c.req.raw));

// Expose RivetKit to the frontend
app.route("/registry", hono);

// Example HTTP endpoint to join chat room
app.post("/api/join-room/:roomId", async (c) => {
const roomId = c.req.param("roomId");

// Verify authentication
const authResult = await auth.api.getSession({
headers: c.req.header(),
});

if (!authResult?.session || !authResult?.user) {
return c.json({ error: "Unauthorized" }, 401);
}

try {
const room = client.chatRoom.getOrCreate(roomId);
const messages = await room.getMessages();

return c.json({
success: true,
roomId,
messages,
user: authResult.user
});
} catch (error) {
return c.json({ error: "Failed to join room" }, 500);
}
});

serve({ fetch: app.fetch, port: 6420 }, () =>
console.log("Listening at http://localhost:6420"),
);
// import { registry } from "./registry";
// import { auth } from "./auth";
// import { Hono } from "hono";
// import { serve } from "@hono/node-server";
//
// // Setup router
// const app = new Hono();
//
// // Start RivetKit
// const { client, hono } = registry.run({
// driver: createMemoryDriver(),
// cors: {
// // IMPORTANT: Configure origins in production
// origin: "*",
// },
// });
//
// // Mount Better Auth routes
// app.on(["GET", "POST"], "/api/auth/**", (c) => auth.handler(c.req.raw));
//
// // Expose RivetKit to the frontend
// app.route("/registry", hono);
//
// // Example HTTP endpoint to join chat room
// app.post("/api/join-room/:roomId", async (c) => {
// const roomId = c.req.param("roomId");
//
// // Verify authentication
// const authResult = await auth.api.getSession({
// headers: c.req.header(),
// });
//
// if (!authResult?.session || !authResult?.user) {
// return c.json({ error: "Unauthorized" }, 401);
// }
//
// try {
// const room = client.chatRoom.getOrCreate(roomId);
// const messages = await room.getMessages();
//
// return c.json({
// success: true,
// roomId,
// messages,
// user: authResult.user
// });
// } catch (error) {
// return c.json({ error: "Failed to join room" }, 500);
// }
// });
//
// serve({ fetch: app.fetch, port: 6420 }, () =>
// console.log("Listening at http://localhost:6420"),
// );
Loading
Loading