How to silently refresh session (triggering the session.before.create hooks)
When a user logs in, I check if they belong to any orgs, and set the
activeOrganizationId in session.before.create, if they do. I also add member_id and member_role to the session, for quick access.
But when they change active org, the hook doesn't seem to rerun. The activeorganizationId changes, but the other fields I've added don't.
Can I manually create and set a new session silently, given that the user is already authenticated13 Replies
Any thoughts/progress with this? Also looking to do something similar
Solution
You're looking to use
update hook instead in this caseThank you
Makes sense, I'll give that a try
Sorry, I actually already tried this. It might just be a type issue, but the
session arg in databaseHooks.session.update.before is Partial, whereas the one in the create.before hook isn't. So if I just do an identity function in the update.before hook, TS shouts:
It's not just a type error. The above logs:
{ activeOrganizationId: '6e762d55-c45c-493c-ae77-24d5fc914a34' } session.update.before
So am I expected to fill in the rest of the session values?
Can I get some help on this, the session.update.before hook appears to have different behaviour to the create versionHey you should unmark it as solved if you still have the issue
I am not following what's the problem and what's the expected outcome.
Are you sure you should use
before and not after hook here?
Have you tried using both in tandem?Options | Better Auth
Better Auth configuration options reference.
I wasn't sure how to do that
When a user signs in, I grab the first org they're a member of, and set the orgId on the new session. I also set the memberId and memberRole for quick access.
This happens in session.create.before
The issue is that when a user changes their active org, the session.create.before hook doesn't run, makes sense.
So I tried hooking into session.update.before to do the same thing, but the data available in the callback is different from the create.before hook
There isn't enough data available to determine the user and member
The only field available in the session.update.before callback is activeOrganizationId
Maybe if you add them as custom fields, they will be infered correctly in the update hook
Even so
ctx is undefined, and the only session field returned is active orgIdI can't get it to fire on user login at all, don't know why
The type error can be mitigated with
It's not just a type error, the fields aren't there at runtime either.
The only field available on session is activeOrgId
Github issue: https://github.com/better-auth/better-auth/issues/4767
GitHub
The data in
databaseHooks.session.update.before is limited compar...Is this suited for github? Yes, this is suited for github To Reproduce Add the following databaseHooks: databaseHooks: { session: { create: { before: async (session, ctx) => { console.log(sessio...