Creating an org at user creation best practices
Hi,
I'm wondering what the best practice is around creating an organization around user-creation
I went to create the organisation after the users name and set it as there active organization
I assume it’s using the database hook paired with my orm qafter user creation? so oauth sign in works too
5 Replies
Use a database hook for user creation and then add a organization and also edit the new sesssion
My current working implementation is a
session.create.before
database hook
I then do some db queries to check if the user is in an organization if they are, add the first organization id to the session's activeOrganizationId
Otherwise insert a new organization, add the user as an owner & then add the org id to the sessions activeOrganizationId
I am not sure if user,create.after
finishes before session.create.before
so i just did it inside session.create.before
to be safeYou really should use database hooks like already advised. Querying the database every time a session is created causes a lot of unnecessary overload. The user is created before the session so
user.create.after
should most definitely finish before session.create.before
.The docs does suggest to query the DB to add the organizationId to the session https://www.better-auth.com/docs/plugins/organization#set-active-organization
But yea i should probably split the logic out, the org creation for
user.create
& active org to session.create
You are doing a-lot of unnecessary queries adding to time by changing your hook you can reduce the amount of db calls needed
With session create their is no way to see if a user has a org or not without querying the db, where as using the create user hook you no longer need to check if you need to create an org you just create one, since if they are new ofc they wont have one.