Best way to run code after user logs in/out

Looking for the best way to run code after a user logs in/out of the app. I need all the users info from the DB obj, the same info that would be returned with authClient.useSession() on a page
11 Replies
bekacru
bekacru5w ago
Hooks | Better Auth
Better Auth Hooks let you customize BetterAuth's behavior
Woffer12
Woffer12OP5w ago
Is the user object returned in the context anywhere?
Ping
Ping5w ago
You can run this:
const session = await getSessionFromCtx(ctx);
const session = await getSessionFromCtx(ctx);
Woffer12
Woffer12OP5w ago
Ok cool I’ll try that, where is that in the docs? I must have missed its mention :LUL:
Ping
Ping5w ago
No it's not your fault, it's in another part of the docs which you wouldn't had thought to look in 😅 https://www.better-auth.com/docs/concepts/plugins#getsessionfromctx There are a lot of functions that utilize ctx and give you something in return, so these functions are usually documented where it would most likely be used at, hard to document the same functions everywhere if you understand me
Plugins | Better Auth
Learn how to use plugins with Better Auth.
Woffer12
Woffer12OP4w ago
Ah gotcha alright, thanks again I’ll try it out and let you know if I run into problems It does indeed work. iThough i am now running into the question of how to add data to a user obj? Like say a user signs up with discord social auth and we add field A to the object, now we are working on a new feature and also need to set a field B which defaults with some info from the sovial provider (discord in this case). If i just add it to the mapProfileToUser config in the socialProviders confirg it does not work, since i am assuming that code only works when a new user is created, but I want to make sure this info is set whenever the user signs in next. Does that make any sense? lol
Ping
Ping4w ago
I think that should had worked, right? @bekacru If someone signs back in to your app using Discord oauth, it should use mapProfileToUser again
bekacru
bekacru4w ago
this hasn't been possible before but already opend a PR. It'll be merged later today https://github.com/better-auth/better-auth/pull/2148
Woffer12
Woffer12OP4w ago
Epic When will this go to stable?
bekacru
bekacru4w ago
this week
Woffer12
Woffer12OP4w ago
Awesome

Did you find this page helpful?