Skip to content
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
55 changes: 55 additions & 0 deletions examples/better-auth/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Better Auth Integration for RivetKit

Example project demonstrating authentication integration with [RivetKit](https://rivetkit.org) using Better Auth.

[Learn More →](https://github.com/rivet-gg/rivetkit)

[Discord](https://rivet.gg/discord) — [Documentation](https://rivetkit.org) — [Issues](https://github.com/rivet-gg/rivetkit/issues)

## Getting Started

### Prerequisites

- Node.js 18+
- npm or pnpm

### Installation

```sh
git clone https://github.com/rivet-gg/rivetkit
cd rivetkit/examples/better-auth
npm install
```

### Development

```sh
npm run dev
```

Open your browser to `http://localhost:5173` to see the frontend and the backend will be running on `http://localhost:6420`.

## Features

- **Authentication**: Email/password authentication using Better Auth
- **Protected Workers**: RivetKit workers with authentication via `onAuth` hook
- **Real-time Chat**: Authenticated chat room with real-time messaging
- **SQLite Database**: Persistent user data and session storage

## How It Works

1. **Better Auth Setup**: Configured with SQLite adapter for user storage
2. **Protected Worker**: The `chatRoom` worker uses the `onAuth` hook to verify user sessions
3. **Frontend Integration**: React components handle authentication flow and chat interface
4. **Session Management**: Better Auth handles session creation, validation, and cleanup

## Key Files

- `src/backend/auth.ts` - Better Auth configuration with SQLite
- `src/backend/registry.ts` - RivetKit worker with authentication
- `src/frontend/components/AuthForm.tsx` - Login/signup form
- `src/frontend/components/ChatRoom.tsx` - Authenticated chat interface

## License

Apache 2.0
41 changes: 41 additions & 0 deletions examples/better-auth/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"name": "example-better-auth",
"version": "0.9.0-rc.1",
"private": true,
"type": "module",
"scripts": {
"dev": "concurrently \"npm run dev:backend\" \"npm run dev:frontend\"",
"dev:backend": "tsx --watch src/backend/server.ts",
"dev:frontend": "vite",
"build": "vite build",
"check-types": "tsc --noEmit",
"test": "vitest run"
},
"devDependencies": {
"@types/node": "^22.13.9",
"@types/react": "^18.2.0",
"@types/react-dom": "^18.2.0",
"@vitejs/plugin-react": "^4.2.0",
"concurrently": "^8.2.2",
"rivetkit": "workspace:*",
"tsx": "^3.12.7",
"typescript": "^5.5.2",
"vite": "^5.0.0",
"vitest": "^3.1.1"
},
"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"
},
Comment on lines +26 to +34
Copy link

Choose a reason for hiding this comment

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

The dependencies section is missing the @better-auth/sqlite package which is imported in src/backend/auth.ts. This will cause a runtime error when the application tries to use the SQLite adapter. Please add @better-auth/sqlite to the dependencies in package.json.

Suggested change
"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"
},
"dependencies": {
"@better-auth/sqlite": "^1.0.0",
"@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"
},

Spotted by Diamond

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

Comment on lines +26 to +34
Copy link

Choose a reason for hiding this comment

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

The better-sqlite3 package is imported in src/backend/auth.ts but missing from the dependencies section in package.json. This will cause a runtime error when attempting to create a new SQLite database. Please add better-sqlite3 to the dependencies to ensure the application functions correctly.

Suggested change
"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"
},
"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",
"better-sqlite3": "^8.6.0",
"hono": "^4.7.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},

Spotted by Diamond

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

"example": {
"platforms": [
"*"
]
},
"stableVersion": "0.8.0"
}
20 changes: 20 additions & 0 deletions examples/better-auth/src/backend/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +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;
48 changes: 48 additions & 0 deletions examples/better-auth/src/backend/registry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { worker, setup } from "rivetkit";
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;
55 changes: 55 additions & 0 deletions examples/better-auth/src/backend/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
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"),
);
73 changes: 73 additions & 0 deletions examples/better-auth/src/frontend/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { useState, useEffect } from "react";
import { authClient } from "./auth-client";
import { AuthForm } from "./components/AuthForm";
import { ChatRoom } from "./components/ChatRoom";

function App() {
const [user, setUser] = useState<{ id: string; email: string } | null>(null);
const [loading, setLoading] = useState(true);

useEffect(() => {
// Check if user is already authenticated
const checkAuth = async () => {
try {
const session = await authClient.getSession();
if (session.data?.user) {
setUser(session.data.user);
}
} catch (error) {
console.error("Auth check failed:", error);
} finally {
setLoading(false);
}
};

checkAuth();
}, []);

const handleAuthSuccess = async () => {
try {
const session = await authClient.getSession();
if (session.data?.user) {
setUser(session.data.user);
}
} catch (error) {
console.error("Failed to get user after auth:", error);
}
};

const handleSignOut = () => {
setUser(null);
};

if (loading) {
return (
<div style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "100vh"
}}>
Loading...
</div>
);
}

return (
<div style={{ minHeight: "100vh", backgroundColor: "#f0f0f0" }}>
<div style={{ padding: "20px 0" }}>
<h1 style={{ textAlign: "center", marginBottom: "30px" }}>
RivetKit with Better Auth
</h1>

{user ? (
<ChatRoom user={user} onSignOut={handleSignOut} />
) : (
<AuthForm onAuthSuccess={handleAuthSuccess} />
)}
</div>
</div>
);
}

export default App;
5 changes: 5 additions & 0 deletions examples/better-auth/src/frontend/auth-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { createAuthClient } from "better-auth/react";

export const authClient = createAuthClient({
baseURL: "http://localhost:6420",
});
Loading
Loading