1+ import {
2+ BetterAuth ,
3+ type AuthFunctions ,
4+ type PublicAuthFunctions ,
5+ } from "@convex-dev/better-auth" ;
6+ import { api , components , internal } from "./_generated/api" ;
7+ import { query } from "./_generated/server" ;
8+ import type { Id , DataModel } from "./_generated/dataModel" ;
9+
10+ // Typesafe way to pass Convex functions defined in this file
11+ const authFunctions : AuthFunctions = internal . auth
12+ const publicAuthFunctions : PublicAuthFunctions = api . auth ;
13+
14+ // Initialize the component
15+ export const betterAuthComponent = new BetterAuth (
16+ components . betterAuth ,
17+ {
18+ authFunctions,
19+ publicAuthFunctions,
20+ }
21+ ) ;
22+
23+ // These are required named exports
24+ export const {
25+ createUser,
26+ updateUser,
27+ deleteUser,
28+ createSession,
29+ isAuthenticated,
30+ } =
31+ betterAuthComponent . createAuthFunctions < DataModel > ( {
32+ // Must create a user and return the user id
33+ onCreateUser : async ( ctx , user ) => {
34+ return ctx . db . insert ( "users" , {
35+ capabilities : [ ] ,
36+ } ) ;
37+ } ,
38+
39+ // Delete the user when they are deleted from Better Auth
40+ onDeleteUser : async ( ctx , userId ) => {
41+ await ctx . db . delete ( userId as Id < "users" > ) ;
42+ } ,
43+ } ) ;
44+
45+ // Example function for getting the current user
46+ // Feel free to edit, omit, etc.
47+ export const getCurrentUser = query ( {
48+ args : { } ,
49+ handler : async ( ctx ) => {
50+ // Get user data from Better Auth - email, name, image, etc.
51+ const userMetadata = await betterAuthComponent . getAuthUser ( ctx ) ;
52+ if ( ! userMetadata ) {
53+ return null ;
54+ }
55+ // Get user data from your application's database
56+ // (skip this if you have no fields in your users table schema)
57+ const user = await ctx . db . get ( userMetadata . userId as Id < "users" > ) ;
58+ return {
59+ ...user ,
60+ ...userMetadata ,
61+ } ;
62+ } ,
63+ } ) ;
0 commit comments