-
Notifications
You must be signed in to change notification settings - Fork 41
chore: add more platform demos #1000
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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 |
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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The
Suggested change
Spotted by Diamond |
||||||||||||||||||||||||||||||||||||||||
"example": { | ||||||||||||||||||||||||||||||||||||||||
"platforms": [ | ||||||||||||||||||||||||||||||||||||||||
"*" | ||||||||||||||||||||||||||||||||||||||||
] | ||||||||||||||||||||||||||||||||||||||||
}, | ||||||||||||||||||||||||||||||||||||||||
"stableVersion": "0.8.0" | ||||||||||||||||||||||||||||||||||||||||
} |
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; |
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; |
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"), | ||
); |
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; |
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", | ||
}); |
There was a problem hiding this comment.
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 insrc/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 inpackage.json
.Spotted by Diamond
Is this helpful? React 👍 or 👎 to let us know.