BA
Better Auth•3mo ago
Brian

Modify User database creation

Hello! 👋 I'm migrating from Auth.js (Next-auth v5). My project currently has an authAdapter with a custom createUser function, which creates an org for a new user. This means that my db has a column: default_org_id which is a required field. How can I modify better-auth's user creation behavior to add my custom org and Stripe creation logic? Additionally, how can I access this required field in the user passed in the customSession() function? customSession(async ({ user, session }) => { user.default_org_id } does not exist here. Thanks!
1 Reply
ctrl-z
ctrl-z•3mo ago
I'm still new at this but perhaps these pointers might help you. Afaik, you can declare new fields in your auth.ts intialization code (then generate and migrate the new schema using @better-auth/cli). The new fields can be defiined this way
// auth.ts

export const auth = betterAuth({
database: ...,
plugins: [...],
user: {
additionalFields: {
default_org_id: {
type: "string", required: true
},
}
})
// auth.ts

export const auth = betterAuth({
database: ...,
plugins: [...],
user: {
additionalFields: {
default_org_id: {
type: "string", required: true
},
}
})
This new field should now be returned via the normal useSession and getSession functions. I'm not entirely sure I understand the situation with your custom createUser function. I recently had to write a custom database adapter but as far as I know, all an adapter does is translate the better-auth queries and where clauses into the target database's api. Maybe this is where lifecycle hooks may be of use. Here is the adapter I recently wrote in case browsing its main file remult-ba.ts might be useful https://github.com/nerdfolio/remult-better-auth/tree/main/src

Did you find this page helpful?