BA
Better Auth•3mo ago
hamish

accessing plugins in DB hooks

Just a question if it's possible or not to access plugins in the DB hooks. good example is creating an organisation when a user signs up? looked around the docs and couldn't find much
15 Replies
nikatune
nikatune•3mo ago
check api path from console when user create and create a database hook with that path
Ping
Ping•3mo ago
Yes you can.
hamish
hamishOP•3mo ago
Do you have an example? I have something like this,
databaseHooks: {
user: {
create: {
after: async (user: User, ctx: GenericEndpointContext) => {
try {
const org = await organization().endpoints.createOrganization({
body: {
name: "test",
slug: "test",
},
headers: ctx.headers,
});
} catch (e) {
console.error("Failed to create org", e);
}
return Promise.resolve();
},
},
},
databaseHooks: {
user: {
create: {
after: async (user: User, ctx: GenericEndpointContext) => {
try {
const org = await organization().endpoints.createOrganization({
body: {
name: "test",
slug: "test",
},
headers: ctx.headers,
});
} catch (e) {
console.error("Failed to create org", e);
}
return Promise.resolve();
},
},
},
Ping
Ping•3mo ago
why not just use auth.api.createOrganization?
hamish
hamishOP•3mo ago
because auth isn't instantiated yet.. It's like const config = { // better auth config here } export const auth = betterAuth(config);
Ping
Ping•3mo ago
You're going to need to move the databaseHook part of your config straight into betterAuth , this way you can access auth
hamish
hamishOP•3mo ago
Such as?
Solution
Ping
Ping•3mo ago
No description
hamish
hamishOP•3mo ago
I may be missing something, but the plugin isn't registered yet?
No description
Ping
Ping•3mo ago
Mimicked your setup, everything works for me. Could it be the type issues regarding the after function causing it?
No description
hamish
hamishOP•3mo ago
Yeah I can't access it inside the hook but can access it when its called after const auth = betterAuth(); auth.api.createOrganization // works
Ping
Ping•3mo ago
Not sure why you're having this issue, but this flow is very common. I often see people create orgs right in the DB hooks. 🤔
hamish
hamishOP•2mo ago
I wonder if it's my tsconfig, I'm using t3-turbo as the base of my project if that helps? How do we pass the headers? is there a way to infer the headers from inside the after function to pass them on?
Ping
Ping•2mo ago
No, however some apis such as createOrganization can be ran without headers as long as you provide a userID
hamish
hamishOP•2mo ago
Yeah that makes sense and is working now

Did you find this page helpful?