create organization in databaseHooks.user.create.after

I want to ensure that for all created users without an invite link, an organization (using the organization plugin) is created for them automatically on sign up. Ideally also set this freshly created organization as their active organization on the client. Is there a way to create an organization for a user that has just been created? I was thinking of using this database hook:
const auth = betterAuth({
database: mongodbAdapter(client.db()),
plugins: [
organization({ allowUserToCreateOrganization: false })
],
databaseHooks: {
user: {
create: {
after: async (user) => {
// create organization for user - can't access the server auth api, can I?
}
}
}
},
// ...
})
const auth = betterAuth({
database: mongodbAdapter(client.db()),
plugins: [
organization({ allowUserToCreateOrganization: false })
],
databaseHooks: {
user: {
create: {
after: async (user) => {
// create organization for user - can't access the server auth api, can I?
}
}
}
},
// ...
})
Any workarounds or solutions for this? Thank you!
Solution:
To follow up ^^, here is how you can create org from server auth api:
No description
Jump to solution
5 Replies
samuelwhunter
samuelwhunter3w ago
That sounds doable! Maybe try taking the path from the context as it'll be different from users that accept an invite. As for the hook, just create a function in a lib file?
after: async (user, ctx) => {
if (ctx?.path.startsWith("/verify-email")) {
// whatever path this actually is
await createNewOrg(user)
// create the account and set as active in here?
}
}
after: async (user, ctx) => {
if (ctx?.path.startsWith("/verify-email")) {
// whatever path this actually is
await createNewOrg(user)
// create the account and set as active in here?
}
}
Hoping I haven't missed the mark here haha
Solution
Ping
Ping3w ago
To follow up ^^, here is how you can create org from server auth api:
No description
hunita
hunitaOP3w ago
Thank you for the replies! I'm not sure if I'm missing something, but since the hook si defined inside the auth instantiation options, I cannot call auth.api.createOrganization from within, can I?
const auth = betterAuth({
// ...
databaseHooks: {
user: {
create: {
after: async (user) => {
auth.api.createOrganization({ ... })
// ^^^^
}
}
}
},
// ...
})
const auth = betterAuth({
// ...
databaseHooks: {
user: {
create: {
after: async (user) => {
auth.api.createOrganization({ ... })
// ^^^^
}
}
}
},
// ...
})
Ping
Ping3w ago
No, this is totally valid
hunita
hunitaOP3w ago
thank you!

Did you find this page helpful?