BA
Better Auth•2d ago
srd

Get user inside session hook

Is there a way to get the userinfo inside a before session databaseHook? I can't call auth.api.getSession and then read the user object as its in the initialization of auth. My goal is to automatically set the active org based on the email domain.
export const auth = betterAuth({

databaseHooks: {
session: {
create: {
before: async (session) => {
const email = user.email
const orgs = orgs
const user_org = some logic to find the correct org based on email
return {
data: {
...session,
activeOrganizationId: user_org.id
}
}
}
}
}
}
});
export const auth = betterAuth({

databaseHooks: {
session: {
create: {
before: async (session) => {
const email = user.email
const orgs = orgs
const user_org = some logic to find the correct org based on email
return {
data: {
...session,
activeOrganizationId: user_org.id
}
}
}
}
}
}
});
2 Replies
srd
srdOP•2d ago
by the looks of it, i would need to do my own db call inside it right to get the wanted info? I think this is the best, and then add the user as a member to the org upon account creation. User will only be connected to one org anyways
databaseHooks: {
session: {
create: {
before: async (session) => {
const [rows] = await db.execute(
'SELECT organizationId FROM member WHERE userId = ? LIMIT 1',
[session.userId]
);
const org = rows[0]?.organizationId ?? null;
return {
data: {
...session,
activeOrganizationId: org
}
}
}
}
}
}
databaseHooks: {
session: {
create: {
before: async (session) => {
const [rows] = await db.execute(
'SELECT organizationId FROM member WHERE userId = ? LIMIT 1',
[session.userId]
);
const org = rows[0]?.organizationId ?? null;
return {
data: {
...session,
activeOrganizationId: org
}
}
}
}
}
}
Ping
Ping•2d ago
My goal is to automatically set the active org based on the email domain
I recommend using after hook for user update user: update: after Then see if email domain changed, then set active org - sort of thing If you know what I mean 😆

Did you find this page helpful?