Skip to content
This repository was archived by the owner on Oct 22, 2025. It is now read-only.

Commit 4c9140a

Browse files
committed
feat: uncomment better-auth example code and fix auth type (#1022)
1 parent b4e243e commit 4c9140a

File tree

7 files changed

+211
-210
lines changed

7 files changed

+211
-210
lines changed
Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,21 @@
1-
// import { betterAuth } from "better-auth";
2-
// import { sqliteAdapter } from "@better-auth/sqlite";
3-
// import Database from "better-sqlite3";
4-
//
5-
// const db = new Database("./auth.db");
6-
//
7-
// export const auth = betterAuth({
8-
// database: sqliteAdapter(db),
9-
// emailAndPassword: {
10-
// enabled: true,
11-
// },
12-
// session: {
13-
// expiresIn: 60 * 60 * 24 * 7, // 7 days
14-
// updateAge: 60 * 60 * 24, // 1 day (every day the session expiry is updated)
15-
// },
16-
// plugins: [],
17-
// });
18-
//
19-
// export type Session = typeof auth.$Infer.Session;
20-
// export type User = typeof auth.$Infer.User;
1+
import { betterAuth } from "better-auth";
2+
import { sqliteAdapter } from "@better-auth/sqlite";
3+
import Database from "better-sqlite3";
4+
5+
const db = new Database("./auth.db");
6+
7+
export const auth = betterAuth({
8+
// IMPORTANT: Connect your own database here
9+
database: sqliteAdapter(db),
10+
emailAndPassword: {
11+
enabled: true,
12+
},
13+
session: {
14+
expiresIn: 60 * 60 * 24 * 7, // 7 days
15+
updateAge: 60 * 60 * 24, // 1 day (every day the session expiry is updated)
16+
},
17+
plugins: [],
18+
});
19+
20+
export type Session = typeof auth.$Infer.Session;
21+
export type User = typeof auth.$Infer.User;
Lines changed: 47 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,47 @@
1-
// import { actor, setup } from "@rivetkit/actor";
2-
// import { auth, type Session, type User } from "./auth";
3-
//
4-
// export const chatRoom = actor({
5-
// onAuth: async (c) => {
6-
// const authResult = await auth.api.getSession({
7-
// headers: c.req.headers,
8-
// });
9-
//
10-
// if (!authResult?.session || !authResult?.user) {
11-
// throw new Error("Unauthorized");
12-
// }
13-
//
14-
// return {
15-
// userId: authResult.user.id,
16-
// user: authResult.user,
17-
// session: authResult.session,
18-
// };
19-
// },
20-
// state: {
21-
// messages: [] as Array<{ id: string; userId: string; username: string; message: string; timestamp: number }>
22-
// },
23-
// actions: {
24-
// sendMessage: (c, message: string) => {
25-
// const newMessage = {
26-
// id: crypto.randomUUID(),
27-
// userId: c.auth.userId,
28-
// username: c.auth.user.email,
29-
// message,
30-
// timestamp: Date.now(),
31-
// };
32-
//
33-
// c.state.messages.push(newMessage);
34-
// c.broadcast("newMessage", newMessage);
35-
//
36-
// return newMessage;
37-
// },
38-
// getMessages: (c) => {
39-
// return c.state.messages;
40-
// },
41-
// },
42-
// });
43-
//
44-
// export const registry = setup({
45-
// use: { chatRoom },
46-
// });
47-
//
1+
import { actor, setup } from "@rivetkit/actor";
2+
import { auth, type Session, type User } from "./auth";
3+
4+
export const chatRoom = actor({
5+
onAuth: async (c) => {
6+
const authResult = await auth.api.getSession({
7+
headers: c.req.headers,
8+
});
9+
10+
if (!authResult?.session || !authResult?.user) {
11+
throw new Error("Unauthorized");
12+
}
13+
14+
return {
15+
userId: authResult.user.id,
16+
user: authResult.user,
17+
session: authResult.session,
18+
};
19+
},
20+
state: {
21+
messages: [] as Array<{ id: string; userId: string; username: string; message: string; timestamp: number }>
22+
},
23+
actions: {
24+
sendMessage: (c, message: string) => {
25+
const newMessage = {
26+
id: crypto.randomUUID(),
27+
userId: c.auth.userId,
28+
username: c.auth.user.email,
29+
message,
30+
timestamp: Date.now(),
31+
};
32+
33+
c.state.messages.push(newMessage);
34+
c.broadcast("newMessage", newMessage);
35+
36+
return newMessage;
37+
},
38+
getMessages: (c) => {
39+
return c.state.messages;
40+
},
41+
},
42+
});
43+
44+
export const registry = setup({
45+
use: { chatRoom },
46+
});
47+
Lines changed: 54 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,54 @@
1-
// import { registry } from "./registry";
2-
// import { auth } from "./auth";
3-
// import { Hono } from "hono";
4-
// import { serve } from "@hono/node-server";
5-
//
6-
// // Setup router
7-
// const app = new Hono();
8-
//
9-
// // Start RivetKit
10-
// const { client, hono } = registry.run({
11-
// driver: createMemoryDriver(),
12-
// cors: {
13-
// // IMPORTANT: Configure origins in production
14-
// origin: "*",
15-
// },
16-
// });
17-
//
18-
// // Mount Better Auth routes
19-
// app.on(["GET", "POST"], "/api/auth/**", (c) => auth.handler(c.req.raw));
20-
//
21-
// // Expose RivetKit to the frontend
22-
// app.route("/registry", hono);
23-
//
24-
// // Example HTTP endpoint to join chat room
25-
// app.post("/api/join-room/:roomId", async (c) => {
26-
// const roomId = c.req.param("roomId");
27-
//
28-
// // Verify authentication
29-
// const authResult = await auth.api.getSession({
30-
// headers: c.req.header(),
31-
// });
32-
//
33-
// if (!authResult?.session || !authResult?.user) {
34-
// return c.json({ error: "Unauthorized" }, 401);
35-
// }
36-
//
37-
// try {
38-
// const room = client.chatRoom.getOrCreate(roomId);
39-
// const messages = await room.getMessages();
40-
//
41-
// return c.json({
42-
// success: true,
43-
// roomId,
44-
// messages,
45-
// user: authResult.user
46-
// });
47-
// } catch (error) {
48-
// return c.json({ error: "Failed to join room" }, 500);
49-
// }
50-
// });
51-
//
52-
// serve({ fetch: app.fetch, port: 8080 }, () =>
53-
// console.log("Listening at http://localhost:8080"),
54-
// );
1+
import { registry } from "./registry";
2+
import { auth } from "./auth";
3+
import { Hono } from "hono";
4+
import { serve } from "@hono/node-server";
5+
6+
// Setup router
7+
const app = new Hono();
8+
9+
// Start RivetKit
10+
const { client, hono } = registry.run({
11+
driver: createMemoryDriver(),
12+
cors: {
13+
// IMPORTANT: Configure origins in production
14+
origin: "*",
15+
},
16+
});
17+
18+
// Mount Better Auth routes
19+
app.on(["GET", "POST"], "/api/auth/**", (c) => auth.handler(c.req.raw));
20+
21+
// Expose RivetKit to the frontend
22+
app.route("/registry", hono);
23+
24+
// Example HTTP endpoint to join chat room
25+
app.post("/api/join-room/:roomId", async (c) => {
26+
const roomId = c.req.param("roomId");
27+
28+
// Verify authentication
29+
const authResult = await auth.api.getSession({
30+
headers: c.req.header(),
31+
});
32+
33+
if (!authResult?.session || !authResult?.user) {
34+
return c.json({ error: "Unauthorized" }, 401);
35+
}
36+
37+
try {
38+
const room = client.chatRoom.getOrCreate(roomId);
39+
const messages = await room.getMessages();
40+
41+
return c.json({
42+
success: true,
43+
roomId,
44+
messages,
45+
user: authResult.user
46+
});
47+
} catch (error) {
48+
return c.json({ error: "Failed to join room" }, 500);
49+
}
50+
});
51+
52+
serve({ fetch: app.fetch, port: 8080 }, () =>
53+
console.log("Listening at http://localhost:8080"),
54+
);
Lines changed: 73 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -1,73 +1,73 @@
1-
// import { useState, useEffect } from "react";
2-
// import { authClient } from "./auth-client";
3-
// import { AuthForm } from "./components/AuthForm";
4-
// import { ChatRoom } from "./components/ChatRoom";
5-
//
6-
// function App() {
7-
// const [user, setUser] = useState<{ id: string; email: string } | null>(null);
8-
// const [loading, setLoading] = useState(true);
9-
//
10-
// useEffect(() => {
11-
// // Check if user is already authenticated
12-
// const checkAuth = async () => {
13-
// try {
14-
// const session = await authClient.getSession();
15-
// if (session.data?.user) {
16-
// setUser(session.data.user);
17-
// }
18-
// } catch (error) {
19-
// console.error("Auth check failed:", error);
20-
// } finally {
21-
// setLoading(false);
22-
// }
23-
// };
24-
//
25-
// checkAuth();
26-
// }, []);
27-
//
28-
// const handleAuthSuccess = async () => {
29-
// try {
30-
// const session = await authClient.getSession();
31-
// if (session.data?.user) {
32-
// setUser(session.data.user);
33-
// }
34-
// } catch (error) {
35-
// console.error("Failed to get user after auth:", error);
36-
// }
37-
// };
38-
//
39-
// const handleSignOut = () => {
40-
// setUser(null);
41-
// };
42-
//
43-
// if (loading) {
44-
// return (
45-
// <div style={{
46-
// display: "flex",
47-
// justifyContent: "center",
48-
// alignItems: "center",
49-
// height: "100vh"
50-
// }}>
51-
// Loading...
52-
// </div>
53-
// );
54-
// }
55-
//
56-
// return (
57-
// <div style={{ minHeight: "100vh", backgroundColor: "#f0f0f0" }}>
58-
// <div style={{ padding: "20px 0" }}>
59-
// <h1 style={{ textAlign: "center", marginBottom: "30px" }}>
60-
// RivetKit with Better Auth
61-
// </h1>
62-
//
63-
// {user ? (
64-
// <ChatRoom user={user} onSignOut={handleSignOut} />
65-
// ) : (
66-
// <AuthForm onAuthSuccess={handleAuthSuccess} />
67-
// )}
68-
// </div>
69-
// </div>
70-
// );
71-
// }
72-
//
73-
// export default App;
1+
import { useState, useEffect } from "react";
2+
import { authClient } from "./auth-client";
3+
import { AuthForm } from "./components/AuthForm";
4+
import { ChatRoom } from "./components/ChatRoom";
5+
6+
function App() {
7+
const [user, setUser] = useState<{ id: string; email: string } | null>(null);
8+
const [loading, setLoading] = useState(true);
9+
10+
useEffect(() => {
11+
// Check if user is already authenticated
12+
const checkAuth = async () => {
13+
try {
14+
const session = await authClient.getSession();
15+
if (session.data?.user) {
16+
setUser(session.data.user);
17+
}
18+
} catch (error) {
19+
console.error("Auth check failed:", error);
20+
} finally {
21+
setLoading(false);
22+
}
23+
};
24+
25+
checkAuth();
26+
}, []);
27+
28+
const handleAuthSuccess = async () => {
29+
try {
30+
const session = await authClient.getSession();
31+
if (session.data?.user) {
32+
setUser(session.data.user);
33+
}
34+
} catch (error) {
35+
console.error("Failed to get user after auth:", error);
36+
}
37+
};
38+
39+
const handleSignOut = () => {
40+
setUser(null);
41+
};
42+
43+
if (loading) {
44+
return (
45+
<div style={{
46+
display: "flex",
47+
justifyContent: "center",
48+
alignItems: "center",
49+
height: "100vh"
50+
}}>
51+
Loading...
52+
</div>
53+
);
54+
}
55+
56+
return (
57+
<div style={{ minHeight: "100vh", backgroundColor: "#f0f0f0" }}>
58+
<div style={{ padding: "20px 0" }}>
59+
<h1 style={{ textAlign: "center", marginBottom: "30px" }}>
60+
RivetKit with Better Auth
61+
</h1>
62+
63+
{user ? (
64+
<ChatRoom user={user} onSignOut={handleSignOut} />
65+
) : (
66+
<AuthForm onAuthSuccess={handleAuthSuccess} />
67+
)}
68+
</div>
69+
</div>
70+
);
71+
}
72+
73+
export default App;

0 commit comments

Comments
 (0)