Is there a recommended way to use the auth.api in after hooks?

Couldn't find this from search so making a new thread for this question... I'm working on adding dynamic redirect after login based upon organization onboarding state.

Goal: The idea is that a user should be redirected from the oauth /callback/:id for social sign in directly to /org-onboarding if the user is a member of an organization that didn't complete onboarding.

Problem: If I use auth.api.getFullOrganization() inside of hooks.after locally, I see that the Better Auth throws a APIError 401. (I assume this is because using await headers() to get the headers from nextjs are missing the Better Auth headers on the oauth callback.

Context

Today, users social sign-in with Github, it makes an oauth callback to the Better Auth endpoint and then they land on the root page. From the root layout.tsx, we use the auth.api.getFullOrganization() to look at metadata about their Better Auth organization an optionally redirect them to an org onboarding flow. The problem with this approach is that it is slow and for a brief moment users see a blank root page. (Layout and Page load in parallel in NextJS apps)

What I tried:
I did see that within the after hook we can get the response headers. https://www.better-auth.com/docs/concepts/hooks#response-headers However, when I pass in these to auth.api.getFullOrganization(), we still get the 401. I logged out what was in the response headers to debug and discovered that it's just an empty object.
Better Auth Hooks let you customize BetterAuth's behavior
Solution
using the builtin adapter
betterAuth({
  hooks: {
   after: createAuthMiddleware(async(ctx)=> {
        const session = ctx.context.newSession // this will give you the newly created session that's about to be set
        const member = await ctx.context.adapter.findOne({
          model: "member",
          where: [ { field:"userId", value: session.user.id } ]
        })
        const orgId = member.organizationId // using orgId fetch the org or do something...
   })
  }
})
Was this page helpful?